ASP. NET MVC Array Model binding

Source: Internet
Author: User

Using the razor syntax in ASP., you can easily present the array in the view, and if you want to bind the array model, you will encounter an index break problem, as in the following example:

<input type= "Text" Name= "[0]. Name "/>

<input type= "Text" Name= "[1]. Name "/>

<input type= "Text" Name= "[2]. Name "/>

<input type= "Text" Name= "[4]. Name "/>

<input type= "Text" Name= "[5]. Name "/>

The array name breaks at index 3, and after the model binder parsing is complete, the subsequent 4 and 5 are discarded, and only 0, 1, 2 are parsed correctly into the corresponding model.

This break occurs frequently during dynamic array binding.

The following is a case study of how to do dynamic array binding. Suppose you have the following scenarios:

Request to be able to dynamically add and delete passengers, the final submission of the form after the passenger information to fill in the view model of an array or collection properties, so as to facilitate our subsequent business processing.

Method One: Replace with placeholder

The first way I call this placeholder substitution is to use the default model binder (Defaultmodelbinder) of the ASP. NET MVC and combine the front-end processing.

First, the first step is to design the view model based on the business scenario:

    public class Ordermodel {//<summary>/////        </summary> public        string Flightno {get; set;}        <summary>/////        </summary> public        list<passenger> passengers {get; set;}    } Public    class passenger    {public        string Name {get; set;}        public string Idno {get; set;}    }

Next, pass this view model to the view:

        Public ActionResult New ()        {            Models.ordermodel Ordermodel = new Models.ordermodel ();            list<models.passenger> passenger = new list<models.passenger> ();            Passenger. ADD (New Models.passenger ());            Ordermodel.passengers = passenger;            Return View (Ordermodel);        }

Then show in the view file:

    <div style= "width:680px" > <div class= "form-group" > <label> flight </label><br/&            Gt @Html. textboxfor (p = p.flightno, new {placeholder = "flight Number"}) </div> <div class= "Form-group"            ;                    <label> Flight person </label> <table class= "Passenger" > <tbody> @if (model.passengers! = null && Model.Passengers.Count > 0) {for (int i = 0; i < Mo Del. Passengers.count;                                i++) {<tr> <td> name:</td> <td> @Html. textboxfor (p = model.passengers[i]. Name) </td> <td> Social Security number:</td> <td> @Html. Textboxfor (p = model.passengers[i]. Idno) </td> <td> <a href= "JavascrIPT: "onclick=" Removepassenger (This) "> Delete </a> </td>            </tr>}} </tbody> </table> <div style= "margin-top:10px" > <a href= "javascript:;" onclick= "Addpassenger ()" > Add Flight Person </ a> </div> </div> </div>

Because the model binder (Defaultmodelbinder) for the ASP. NET MVC has the ability to automatically parse shapes like "[0]. Property name", "[1]. Property name", you can represent the array subscript in the template file as a placeholder:

<!--flight template--><script type= "text/html" id= "passengertemplate" >    <tr>        <td> Name: </td >        <td><input id= "Passengers_{}__name" Name= "passengers[{}". Name "type=" text "value=" "></td>        <td> ID number:</td>        <td><input id=" passengers_{ }__idno "Name=" passengers[{}]. Idno "type=" text "value=" "></td>        <td>            <a href=" javascript:; "onclick=" Removepassenger ( This) "> delete </a>        </td>    </tr></script>

The "{}" in the code above is an array subscript placeholder. When you add a flight, you can pre-calculate the number of people you already have, and then use JavaScript to replace the "{}" for an array subscript.

    Add Flight person    function Addpassenger () {        //Current add row array element subscript        var index = $ (". Passenger"). Find ("Tbody"). Find ("tr"). length;        {} is an array-element subscript placeholder        var passengerhtml = $ (' #passengerTemplate '). html (). Replace (/{}/g, index);        $ (". Passenger"). Find ("Tbody"). Append (passengerhtml);    }

When a flight is deleted, Note If the deletion is not the last one, an index break problem will occur and the array subscript needs to be re-adjusted :

    Remove the flight person    function Removepassenger (e) {        $ (E). Parents ("tr"). Remove ();        Iterate through each row of the table, re-adjust the array subscript        var = $ (". Passenger"). First ();        var count = Tb.find ("Tbody"). Find ("tr"). Length;        for (var i = 0; i < count; i++) {            var newtr = Tb.find ("tr"). EQ (i). formhtml (). Replace (/\[\d+\]/g, ' [' + i + '] ');// Re-adjusts the array element subscript            tb.find ("tr"). EQ (i). html (NEWTR);        }    }

This way, when we submit the form, the flight information is automatically populated into the model's passengers attribute.

Mode two: Use Vue.js

Using the first method requires writing a lot of front-end code, including template files, adding delete events, and also dealing with interpolation issues when the reorder is in order.

If using the front-end MVVM framework makes this process simple, the Popular Front-end MVVM framework is angularjs, with antique knockoutjs and emerging niche frameworks vue.js.

Angularjs is quite large, so simple a model binding with anuglar has a sense of overkill, knockout and Vue are lightweight MVVM frameworks, but knockout needs to wrap native data to make observable objects, The value and assignment need to take the form of function call, it is not very convenient to use, so I chose vue.js. Vue.js is a lightweight and efficient library that has no API like angular module, controller, scope, factory, service, and the core is a model binding feature. The size is only 70kb,gzip compressed after only 25kb, very light weight.

The rationale behind this approach is that the front-end uses vue.js to declare the view model and bind it, and then submits the form to the background by serializing the model as a JSON string, and then deserializing it back into a C # object using Json.NET.

Because of the binding characteristics of vue.js, we only need to manipulate the array elements, without additional attention to DOM operations, saving a lot of effort.

First, you need to declare the view model and bind using Vue.js:

<script src= "~/scripts/vue.js" ></script><script type= "Text/javascript" >//view model Var ViewMo            del = {flightno: ', passengers: [{elementid: ' passenger_1 ', Name: ', Idno: '} ]}//Model binding new Vue ({el: ' #app ', Data:viewmodel, method S: {removepassenger:function (ElementID) {for (var i = 0; i < viewmodel.passengers . length; i++) {if (Viewmodel.passengers[i].                        ElementID = = ElementID) {ViewModel.Passengers.splice (I, 1); }}}, Addpassenger:function () {var TB = DOCUMENT.G                    Etelementsbytagname (' table ') [0];                    var index = tb.rows[tb.rows.length-1].getelementsbytagname (' input ') [0].getattribute ("id"). split ('_') [1]; ViewModel.Passengers.push ({Name:", Idno: ', ElementID: ' Passenger_ ' + (index + 1)});                    }, Submitform:function () {var jsonstring = json.stringify (ViewModel);                    document.getElementById ("ViewModel"). Value = jsonstring;                return true; }});</script>

Then use the vue.js binding in the view:

<form action= "/order2/newpost" method= "POST" > <div id= "App" style= "width:680px" > <div class= "Form -group "> <label> flights </label><br/> <input v-model=" Flightno "type=" text "place            holder= "Flight number"/> </div> <div class= "Form-group" > <label> Flight Person </label> <table class= "Passenger" > <tbody> <tr v-for= "passenger in Passeng ERs "> <td> name:</td> <td><input v-model=" passenger. Name "V-bind:id=" passenger. ElementID "type=" text "/></td> <td> ID number:</td> &LT;TD&GT ; <input v-model= "passenger.  Idno "type=" text "/></td> <td> <a href=" javascript:; " v-on:click= "Removepassenger (passenger. ElementID) "> Delete </a> </td> </tr> </tbody> </table> <div style= " margin-top:10px "> <a href=" javascript:; "v-on:click=" Addpassenger "> Add passengers </a> < /div> <div style= "margin-top:10px" > <input type= "Submit" class= "btn Btn-default" V-o n:click= "SubmitForm"/> </div> </div> </div> <input type= "hidden" id= "view Model "Name=" ViewModel "/></form>

Finally, in the controller, we can get the corresponding C # strongly typed model in deserialization:

        [HttpPost]        Public ActionResult Newpost ()        {            var jsonstring = request.form["ViewModel"];            Models.ordermodel model = newtonsoft.json.jsonconvert.deserializeobject<models.ordermodel> (jsonString);            if (model! = NULL) {                //Our code here ...            }            Return redirecttoaction ("Index", "Home");        

Both of these methods enable dynamic array binding, one using JS for placeholder substitution, and the elements in the form are named with [index]. Property names, and then the model is transformed by the MVC default model binder;

Mode two uses Vue.js to directly model the binding, the model is serialized as a JSON string when the form is submitted, and then the backend is deserialized, resulting in a strongly typed model.

A simple example program (12E5)

ASP. NET MVC Array Model binding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.