asp.net-mvc – 从传递给局部视图的嵌套复杂对象获取值

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 从传递给局部视图的嵌套复杂对象获取值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个viewmodel,它有一个复杂的对象作为其成员之一.复杂对象有4个属性(所有字符串).我正在尝试创建一个可重复使用的部分视图,我可以传入复杂对象,并使用html帮助器为其属性生成html.这一切都很好.但是,当我提交表单时,模型binder不会将值映射回viewmodel的成员,所以我不会在服务器端返回任何东西.我如何读取用户输入复合对象的html帮助器的值.

视图模型

@H_301_4@public class Myviewmodel { public string SomeProperty { get; set; } public MyComplexModel ComplexModel { get; set; } }

MyComplexModel

@H_301_4@public class MyComplexModel { public int id { get; set; } public string Name { get; set; } public string Address { get; set; } .... }

调节器

@H_301_4@public class MyController : Controller { public ActionResult Index() { Myviewmodel model = new Myviewmodel(); model.ComplexModel = new MyComplexModel(); model.ComplexModel.id = 15; return View(model); } [HttpPost] public ActionResult Index(Myviewmodel model) { // model here never has my nested model populated in the partial view return View(model); } }

视图

@H_301_4@@using(Html.BeginForm("Index","MyController",FormMethod.Post)) { .... @Html.Partial("MyPartialView",Model.ComplexModel) }

部分视图

@H_301_4@@model my.path.to.namespace.MyComplexModel @Html.TextBoxFor(m => m.Name) ...

如何在表单提交时绑定此数据,以便父模型包含从局部视图在Web表单上输入的数据?

谢谢

编辑:我已经想到我需要在前面添加“ComplexModel”.在部分视图(文本框)中的所有控件的名称,以便映射到嵌套对象,但是我无法将viewmodel类型传递给部分视图以获取该额外的图层,因为它需要通用才能接受多个viewmodel类型.我可以用javascript重写name属性,但是对我来说似乎是过度贫民窟.我还能怎么做?

编辑2:我可以使用新的{Name =“ComplexModel.Name”}静态设置name属性,所以我认为我有事业,除非有更好的方法

解决方法

您可以将前缀传递给部分使用 @H_301_4@@Html.Partial("MyPartialView",Model.ComplexModel,new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "ComplexModel" }})

这将使前缀变为控制名称属性,以便< input name =“Name”../\u0026gt;将成为< input name =“ComplexModel.Name”../\u0026gt;并正确绑定到类型的Myviewmodel在回发 编辑 为了使它更容易一些,您可以将其封装在一个html帮助器中

@H_301_4@public static MvcHtmlString PartialFor<TModel,TProperty>(this HtmlHelper<TModel> helper,Expression<Func<TModel,TProperty>> expression,string partialViewName) { string name = ExpressionHelper.GetExpressionText(expression); object model = ModelMetadata.FromLambdaExpression(expression,helper.ViewData).Model; var viewData = new ViewDataDictionary(helper.ViewData) { TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = name } }; return helper.Partial(partialViewName,model,viewData); }

并将其用作

@H_301_4@@Html.PartialFor(m => m.ComplexModel,"MyPartialView")

猜你在找的asp.Net相关文章