Url.Action放置& 在我的网址中,我该如何解决?


89

我想将变量itemId和EntityModel发送到ActionResult CreateNote:

public ActionResult CreateNote(
        [ModelBinder(typeof(Models.JsonModelBinder))]
        NoteModel Model, string cmd, long? itemId, string modelEntity)

与此JavaScript:

Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});

但是,正在发送的网址是

localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44     

我想发送

localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44

如何防止Url.Action将&放在要发送的第二个变量前面?


是什么让您认为那&不好呢?
奥德

1
因为当我查看带有断点的ActionResult时,当我拥有localhost:1304 / Administration / blue / en-gb / Entity / CreateNote?modelEntity = Phrase&itemId = 44 modelEntity = Phrase且itemId = null时。当我在javascript中将它们转过来并获得localhost:1304 / Administration / blue / en-gb / Entity / CreateNote?itemId = 44& modelEntity = Phrase itemId = 44和modelEntity = null时。因此,我认为这与&
尼克·克莱因

4
@Oded-因为数据是插入到JavaScript中,而不是HTML中。
昆汀

Answers:


126

昨天我没有注意到您&以为是SO编辑器改变了这一点。尝试将您的包裹Url.Action()@Html.Raw()防止和为Encode。

或者,也可以仅Url.Action()将控制器/操作位作为传递数据,而不是直接在url上传递这两个参数,jQuery应该以这种方式为您整理&。


43
此解决方案有效,但是为什么Url.Action甚至被编码?谈论意外行为。
杰里

13

我认为您的问题在于Model.meta.PostAction-该物业是否string吗?

如果是这样,那么我的猜测是您正在使用以下任一方法将其添加到页面中:

  • 剃刀: @Model.meta.PostAction
  • ASP视图引擎: <%:Model.meta.PostAction%>

两者都会自动为您编码该字符串。

要解决此问题,请使用@Html.Raw()/ <%=(两者均不进行编码),或者使该PostAction属性成为IHtmlString已知已被编码的属性:

string actionUrl = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
Model.meta.PostAction = new HtmlString(actionUrl);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.