1

I have a viewModel in Asp.net mvc5 that contains a object:

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:

        @Html.HiddenFor(x => x.Convenio, new { @id = "convenioJson" })

and my Javascript is this:

$('#convenioJson').val(JSON.stringify(data.List[i]));

My Json is this:

"{'Descricao':'UNIMED                   ','Id':1,'CodigoLogin':'bortolop','DataStamp':'/Date(903621226000)/'}"

but when I submit this form, my property "Convenio " is null. what is the way to populate this in form submit? in ajax I already know

3
  • yep, I´ll edit the question Commented Oct 25, 2016 at 11:45
  • 2
    Convenio is a complex object. You cannot bind a complex object to an input (look at the html your generating). You need an input for each property of the model. BUt what is the point of this - they can't be edited, so if you need the object in the POST method, then just get it again Commented Oct 25, 2016 at 11:45
  • 1
    ok, for each property in my object of viewmodel i need to bind like a input..I really understand Commented Oct 25, 2016 at 11:48

1 Answer 1

4

It doesn't work because String type cannot parse to complex object. 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

ModelBinders.Binders.Add(typeof(ConvenioViewModel), new ConvenioViewModelBinder());

That's all!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.