我有一个控制器HomeController
与以下action method
:
[HttpPost]
public ActionResult DisplayData(MyViewModel myViewModel)
{
// Do something with myViewModel
}
The ViewModel
:
public class MyViewModel
{
public string Name { get; set; }
public string Surname { get; set; }
public bool IsPeriod { get; set; }
}
以及以下内容View
@model AppName.ViewModels.MyViewModel
@{ Html.RenderPartial("MyPartialView", Model); }
<img src="@Url.Action("DisplayData", "Home", new { myViewModel = Model })" alt="Image" />
我使用 Url.Action 的描述方式here但我在 DisplayData 操作方法中得到的是 null。在源代码中我得到:
<img src="/Home/DisplayData?filters=AppName.ViewModels.MyViewModel" alt="Image" />
所以它实际上传递的是类型而不是值。
The ViewModel
相反,它被正确传递到部分视图。我究竟做错了什么?
我通常将以下内容添加到我的模型中:
public class MyViewModel
{
public string Name { get; set; }
public string Surname { get; set; }
public bool IsPeriod { get; set; }
public RouteValueDictionary RouteValues
{
get
{
var rvd = new RouteValueDictionary();
rvd["name"] = Name;
rvd["surname"] = Surname;
rvd["isPeriod"] = IsPeriod;
return rvd;
}
}
}
然后,您可以简单地在 Url.Action() 调用中使用 RouteValues 属性。
<img src="@Url.Action("DisplayData", "Home", Model.RouteValues)" alt="Image" />
或者,如果您更喜欢较少(显式)代码,请忽略模型更改并简单地执行以下操作:
<img src="@Url.Action("DisplayData", "Home", new RouteValueDictionary(Model)" alt="Image" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)