How to enable display of the RadioButtons group in EditorTemplates in ASP.Net MVC (3)

I have a list of elements from which I want the user to enter some value, select one. But the radio buttons created using the EditorTemplate are called "Item [x] .SelectedItemId", so they are completely independent of each other, and i can't get the value ...

Release the code. Model:

public class FormModel { public List<ItemModel> Items { get; set; } public int SelectedItemId { get; set; } } public class ItemModel { public int ItemId { get; set; } public string ItemName { get; set; } public string SomeString { get; set; } } 

View:

 @model FormModel @using (Html.BeginForm()) { @Html.EditorFor(m => m.Items) } 

Editor Template:

 @model ItemModel @Html.RadioButton("SelectedItemId", Model.ItemId) @Model.ItemName <br/> @Html.TextBoxFor(m => m.SomeString) <br/> 

UPDATE

This is what I want:

What i want

This is what I get:

what I get

As a result, FormModel.SelectedItemId never gets the value of any radio button.

What am I doing wrong?

+4
source share
2 answers

It seems that you know that in order to make them work, it is necessary that the names for the switches are the same. However, when you do this in the editor template using the line of code @Html.RadioButton("SelectedItemId", Model.ItemId) , MVC 3 will take into account that you are in the editor template for elements and extra elements [n].

This will create a name like name="Items[0].SelectedIndex" . That would be nice if it weren't for the fact that the next switch would be `name =" Items [1] .SelectedIndex ".

One way to solve this problem is to not use the editor template and use the foreach instead. Here is the code I was able to get. I confirmed that model binding worked for SelectedIndex .

  @model FormModel @{ ViewBag.Title = "Index"; } @using (Html.BeginForm()) { foreach (var item in Model.Items) { @Html.RadioButtonFor(x => x.SelectedItemId, item.ItemId) @item.ItemName <br/> @Html.TextBoxFor(m => item.ItemName) <br/> } <input type="submit" value = "submit" /> } 
+3
source

I had the same problem and we solved it with this part of the code.

 @Html.RadioButton("", Model.Id, Model.Selected, new { Name = "deliveryMethod" }) 

You need to specify the Name property explicitly, so it will be used instead of the name that you get after executing EditorFor .

+1
source

Source: https://habr.com/ru/post/1369153/


All Articles