[英]How bind property in model from json in asp.net mvc5
I have a viewModel in Asp.net mvc5 that contains a object: 我在Asp.net mvc5中有一个包含对象的viewModel:
public class ConvenioViewModel
{
public Convenio Convenio { get; set; }
public string AnotherProperty {get;set;}
}
and I need that this property be populate with a json in Form Submit, because I populate this in input hidden with Json: 并且我需要在Form Submit中用json填充此属性,因为我在用Json隐藏的输入中填充了此属性:
@Html.HiddenFor(x => x.Convenio, new { @id = "convenioJson" })
and my Javascript is this: 我的JavaScript是这样的:
$('#convenioJson').val(JSON.stringify(data.List[i]));
My Json is this: 我的Json是这样的:
"{'Descricao':'UNIMED ','Id':1,'CodigoLogin':'bortolop','DataStamp':'/Date(903621226000)/'}"
but when I submit this form, my property "Convenio " is null. 但是当我提交此表单时,我的属性“ Convenio”为空。 what is the way to populate this in form submit? 在表单提交中填充此内容的方式是什么? in ajax I already know 在阿贾克斯我已经知道
It doesn't work because String type cannot parse to complex object. 它不起作用,因为String类型无法解析为复杂对象。 You should create custom databinder something like this: 您应该创建自定义数据绑定器,如下所示:
public class ConvenioViewModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ConvenioViewModel viewModel = new ConvenioViewModel() {};
string jsonConvenio = bindingContext.ValueProvider.GetValue("convenio").AttemptedValue;
JavaScriptSerializer jss = new JavaScriptSerializer();
viewModel.Convenio = jss.Deserialize<Convenio>(jsonConvenio);
return viewModel;
}
}
In Application_Start() add 在Application_Start()中添加
ModelBinders.Binders.Add(typeof(ConvenioViewModel), new ConvenioViewModelBinder());
That's all! 就这样!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.