Frostless
Frostless

Reputation: 848

Passing multiple checkbox values to deeper level of model .net mvc

A few similar questions have been asked before but my use case is a bit different.

So this is my model:

  public class YourModel
  {
        public string[] Suburb { get; set; }
  }

And my view:

    <input name="Suburb" type="checkbox" value="sydney" /><span>sydney</span>
    <input name="Suburb" type="checkbox" value="melbourne" /><span>melbourne</span>

Controller:

 public ActionResult AdvancedSearch(YourModel s)
 {
      // logic
 }

So MVC is smart enough to retrieve the multiple checkbox values to put them in the Suburb array in YourModel model. I can inspect all values there. But my use case is that the YourModel is just the nested model inside another model MyModel:

  public class MyModel
  {
        //other properties
        public YourModel m { get; set; }
  }

So now how do I make MVC post the checkbox values to a deeper model MyModel.YourModel? I have tried @Html.CheckBoxFor and @Html.CheckBox but neither of them worked.

Right now my work around is to add a temporary array placeholder in the outside model and then assign all the data to the inside model when available, but that is definitely not ideal.

Upvotes: 2

Views: 546

Answers (2)

programtreasures
programtreasures

Reputation: 4298

You need to use add MyModel

<input name="m.Suburb" type="checkbox" value="sydney" /><span>sydney</span>
<input name="m.Suburb" type="checkbox" value="melbourne" /><span>melbourne</span>

Upvotes: 3

Camilo Terevinto
Camilo Terevinto

Reputation: 32058

In Razor, you don't have to define the name of the top-most Model, only the names of the properties of inner models:

<input name="m.Suburb" type="checkbox" value="sydney" /><span>sydney</span>
<input name="m.Suburb" type="checkbox" value="melbourne" /><span>melbourne</span>

However, I'd strongly suggest you to change that m name to something more significant.

Upvotes: 0

Related Questions