Binding a model property to a List<SelectListItem> on Post

mvc model binding to list of complex objects
model binding to a list mvc 5
how to bind list from controller to view in mvc
mvc model binding list of objects
list of model object post to controller in mvc
how to bind list to textbox in mvc
mvc ienumerable model binding
c# mvc list model binding

I'm trying to post the value of the textbox that is clicked, back to the controller. My problem is, no matter what textbox is clicked, the form only posts back the first item within the list. I know I could've used a dropdownlist instead but I ultimately decided against it.

I've got a view where I'm looping through a List<SelectListItem>. Within this loop, I'm creating a textbox for another model property(string) and setting the value of the property to an item within the List<SelectListItem>. I've set the textboxes as readonly and added jquery to submit the form when a textbox is clicked.

The commented JQuery which posts the value of the textbox to the console works fine. It's posting back to the controller where I'm having the issue. I think the problem might be because the JQuery postback is not recognising each individual textbox and instead posts the first item in the list - I might be wrong.

Any help would be greatly appreciated

Here is the view:

 @model TheConnector.ViewModel.SelectAHero
        ViewBag.Title = "Heroes";
        ViewBag.Message = "Here are the Heroes that are currently registered with your account";
    @section Scripts {
        <script type="text/javascript">

            $(document).ready(function () {
                $('.postHeroSelection').click(function () {

    //        $(document).ready(function () {
    //            $('.postHeroSelection').click(function () {
    //                console.log($(this).val());
    //            });
    //        });

                display: none;
        <meta http-equiv="refresh" content="0;url=javascript-error.htm" />
    <div class="full grey_bg auto-height">
        <!-- Full -->
        <div class="content">
            <!-- Content -->
            <div class="container" style="background-color: #ddd">
                <div style="padding: 0px; border: 0px solid black; height: 100px; margin: 0; padding: 10px;">
                    <div style="float: left; border: 0px solid black; padding: 0 0; height: 100%; display: table;">
                @Html.ValidationMessageFor(m => m)
                <div id="RegisterNewHero">
                    @using (Html.BeginForm("Heroes", "User", FormMethod.Post))

                            Please click on one of the following to load a Hero:</h3>
                        <br />

                        for (var i = 0; i < Model.ListOfHeroes.Count; i++)
                        @Html.TextBoxFor(m => m.chosenHero, new { @class = "postHeroSelection", onclick = "return false", @Value = Model.ListOfHeroes[i].Value.ToUpper(), @readonly = "readonly", @id = Model.ListOfHeroes[i].Value })
                        <br />
                        <br />

                        <br />
                        <br />
                        <br />

                <!-- Register -->
                <div class="clear">
            <!-- / Content -->
        <!-- Full  -->

Here is the controller:

            public ActionResult Heroes(SelectAHero model) {


                return RedirectToAction("Index", "User");
                 ModelState.AddModelError("","An error has occurred");

             return View(model);

You have only one form so this "$(this).closest('form').submit();" is unnecessary. You can see what you post by looking to browsers network section(developer tool).

You can basically use <a href="Heroes?id=@yourHeroId"> to pass selected data without using form or js.

And your Controller look like

public ActionResult Heroes(string id){ //whatever you do}

MVC Model with a list of objects as property, public class Item { public List<Colour> AvailableColours { get;set; } Note the for loop insted of foreach to enable model binding and the hidden� The default model binder sees all these name/value pairs with the same name and converts that to a collection with the key ints, which is then matched up with the ints parameter to your action method. Pretty simple! Where it gets trickier is when you want to post a list of complex types. Suppose you have the following class and action method.

i am sorry, now i understand your code. you need add this code in your form.


and change your script to

            $('.postHeroSelection').click(function () {

                document.getElementById("chosenHero").value = $(this).val();// add this line 

now you can access model.chosenHero.

and change your textbox list to

@Html.TextBoxFor(m => m.ListOfHeroes[i].Value
                                        , new {
                                            @class = "postHeroSelection"
                                            , onclick = "return false"
                                            , @readonly = "readonly"
                                            , @id = Model.ListOfHeroes[i].Value

Model Binding to List of Objects in ASP.NET MVC, The single record editing works on the assumption that form field names from the view match the corresponding model property names. Gets the property descriptor that is used for sorting the list if sorting is implemented in a derived class; otherwise, returns null. SupportsChangeNotificationCore: Gets a value indicating whether ListChanged events are enabled. SupportsSearchingCore: Gets a value indicating whether the list supports searching. SupportsSortingCore

It will always post first item with the correspondent name of the form to server. You'll need an auxiliar element (Hidden maybe) to store the value clicked.

In my personal opnion is preferable use DropDownListFor that was created for this purpose.

Model Binding To A List, This ensures we can unambiguously match up the submitted properties with the correct object. Here's an example of a form that submits three� Binding recognizes component parameters, where @bind-{PROPERTY} can bind a property value from a parent component down to a child component. Binding from a child to a parent is covered in the Child-to-parent binding with chained bind section. The following child component (ChildComponent) has a Year component parameter and YearChanged callback:

Simple Way to Bind List of Objects to View Using MVC, cs in the Models folder. It has username, age and Gender as properties. The various attributes have been defined for validations. Adding-Model-� I have a basic ViewModel with a property that is a List of complex types. When binding, I seem to be stuck with getting either the list of values, OR the other model properties depending on the posted values (i.e. the view arrangement). The view model:

[Solved] Mvc bind list of objects, Hi, Go through the link: [^] For deep understanding : ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries - Scott� Relative bindings provide the ability to set the binding source relative to the position of the binding target. They are created with the RelativeSource markup extension, and set as the Source property of a binding expression. The RelativeSource markup extension is supported by the RelativeSourceExtension class, which defines the following

Model Binding in Razor Pages, Model Binding in Razor Pages is the process that takes values from an a long list of properties, all decorated with the BindProperty attribute,� Inside Model Binding. As you have seen that Model binding automatically converts request values into a primitive or complex type object. Model binding is a two step process. First, it collects values from the incoming http request and second, populates primitive type or complex type with these values.

  • So you want all the values of the textboxes in the post method right???
  • @GaganDeep I would like the value of whichever textbox that is clicked to be posted back