简体   繁体   中英

ASP.NET MVC checkbox with Name attribute for corresponding value fields

My Model

public class MyFormField
{
    public List<MyClass> propName { get; set; }
    public string Value { get; set; }
}
public class MyClass
{
    public string Name { get; set; }
}

Am passing List of MyFormField to view

In View

@foreach (var item in Model.propName)
 {

  @Html.TextBoxFor(m => m.Name)
 }

i need to add a checkBox before the textBox like below

@foreach (var item in Model.propName)
 {
 @Html.checkbox("")
  @Html.TextBoxFor(m => m.Name)
 }

and each checkbox should have a unique name attribute as a corresponding textbox. How can i Change my model to acheive this ?

For business need i need a checkbox for each corresponding Textbox or what better way i can achieve in MVC ?

Add to your model:

public class MyClass
{
    public string Name { get; set; }
    public boolean Checked {get;set;}
}

Then add:

@Html.CheckBoxFor(model => item.Checked)
@Html.TextBoxFor(model => item.Name)

That way, each checkbox is assoicated with the MyClass in the list

public class MyClass
{
    public string Name { get; set; }
    public boolean Checked {get;set;}
}

Doing this you would have unique id for each row.

@for (int i = 0; i < Model.propName.Count; i++)
{
    @Html.CheckBoxFor(m => m.propName[i].Checked, new { class = "propName_" + i })
    @Html.TextBoxFor(m => m.propName[i].Name, new { class = "propName_" + i })
}

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