简体   繁体   中英

Pass a list from a view to a controller, MVC 5

So, I'm using MVC, and I'm trying to create a new employee using entity. Along with creating the employee, I am trying to create a list of items that are tied to the employee (one to many).

So my issue is, I am calling a javascript function in the onclick event of the submit button. This javascript function creates a list of IDs, I need these to create the items.

How can I get this list of IDs to my controller, so I can create them?

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" onclick="getResult()"/>
        </div>
    </div>

Add an empty hidden input to the form element in your view, let's call it idslist

@Html.Hidden("idslist")

put your ids in that input using javascript JSON.stringify or simply an id list separated by a separator.

And now you can read that list on your controller, when the user submits the form :

public ActionResult Create(myModel x, string idslist)
{
    // now you have to deserialize your idslist
    // using JsonConvert.DeserializeObject or just split for the second case.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM