我和他的问题大致相同
ASP.NET MVC partial views: input name prefixes
我想为这些数据实体创建CRUD操作:
public class Userviewmodel { protected virtual Id {get; set;} public virtual string Login { get; set; } public virtual string Password { get; set; } public virtual ZipCodeviewmodel ZipCode { get; set; } }
邮政编码实体:
public class ZipCodeviewmodel { public virtual string City { get; set; } public virtual string State { get; set; } public virtual string Zip { get; set; } }
我也有部分视图ZipCode使用Userviewmodel.ZipCode:
@model ZipCodeviewmodel @Html.TextBoxFor(x => x.Zip,new { id = "ZipCode",name = "ZipCode.Zip",maxlength = "5" })
我将在另一个页面(例如用户)中使用ZipCodePartialView.
@model Userviewmodel ..... @{Html.RenderPartial("Zipcode",Model.ZipCode);}
当MVC保存用户ZipCode字段Zip为空时.
那么问题是我如何为patrial View添加模型前缀?
解决方法
试试这个扩展:
public static void RenderPartialWithPrefix(this HtmlHelper helper,string partialViewName,object model,string prefix) { helper.RenderPartial(partialViewName,model,new ViewDataDictionary { TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = prefix } }); }