@Html.HiddenFor does not work on Lists in ASP.NET MVC

后端 未结 13 913
灰色年华
灰色年华 2020-11-27 15:13

I\'m using a model that contains a List as a property. I\'m populating this list with items i grab from SQL Server. I want the List to be hidden in the view and passed to th

13条回答
  •  感情败类
    2020-11-27 15:32

    What about using Newtonsoft to deserialize the object into a json string and then insert that into your Hidden field e.g. (Model.DataResponse.Entity.Commission is a List of simple "CommissionRange" objects as you'll see in the JSON)

    @using (Ajax.BeginForm("Settings", "AffiliateProgram", Model.DataResponse, new AjaxOptions { UpdateTargetId = "result" }))
       {
          string commissionJson = JsonConvert.SerializeObject(Model.DataResponse.Entity.Commission);
          @Html.HiddenFor(data => data.DataResponse.Entity.Guid)
          @Html.Hidden("DataResponse_Entity_Commission", commissionJson)
          [Rest of my form]
       }
    

    Renders as:

    
    

    In my case I do some JS stuff to edit the json in the hidden field before posting back

    In my controller I then use Newtonsoft again to deserialize:

    string jsonCommissionRange = Request.Form["DataResponse_Entity_Commission"];
    List commissionRange = JsonConvert.DeserializeObject>(jsonCommissionRange);
    

提交回复
热议问题