对于我正在处理的应用,我为我正在处理的视图提供了以下Razor代码:
@Html.InputFor(m => m.Property1); // A date
@Html.InputFor(m => m.Property2); // Some other date
@Html.InputFor(m => m.SomeOtherProperty); // Something else.
<a href='#' id='some-button'>Button Text Here</a>
<!-- SNIP: Extra code that dosen't matter -->
<script>
var $someButton = $('#some-button');
$(document).ready(function () {
$someButton.click(function (e) {
e.preventDefault();
window.open('@Url.Action("Foo", "Home", new {p1 = Model.Property1, p2 = Model.Property2, pX = Model.SomeOtherProperty})', '_blank');
});
});
</script>
...评论时,我检查了呈现的HTML。正如预期的那样,值带有值......
<input name="Property1" data-val="true" data-val-required="(Required)" type="text" value="1/1/2013">
<input name="Property2" data-val="true" data-val-required="(Required)" type="text" value="4/11/2013">
<input name="SomeOtherProperty" data-val="true" data-val-required="(Required)" type="text" value="42">
<a href='#' id='some-button'>Button Text Here</a>
<script>
var $someButton = $('#some-button');
$(document).ready(function () {
$someButton.click(function (e) {
e.preventDefault();
window.open('http://localhost:xxxx/Home/Foo?p1=1%2F1%2F2013&p2=4%2F11%2F2013&pX=42', '_blank');
});
});
</script>
......并在服务器端......
public ActionResult Foo(string p1, string p2, string pX)
{
var workModel = new FooWorkModel
{
Property1 = p1,
Property2 = p2,
SomeOtherProperty = pX
};
// Do something with this model, dosen't really matter from here, though.
return new FileContentResult(results, "application/some-mime-type");
}
我注意到只有第一个参数(p1
)从前端获取值;我所有其他参数都传递空值!
问题:为这些其他字段分配了一些值时,为什么ActionResult会传递空值?或者,一个互补的问题:为什么只有第一个参数成功传递其值,而其他一切都失败了?
答案 0 :(得分:2)
问题是由Url.Action()
生成的转义网址引起的。 (来源:How do I pass correct Url.Action to a JQuery method without extra ampersand trouble?)
只需在@Html.Raw()
周围添加Url.Action()
来电,数据就会按预期流动。
window.open('@Html.Raw(Url.Action("Foo", "Home", new {p1 = Model.Property1, p2 = Model.Property2, pX = Model.SomeOtherProperty}))', '_blank');