如何在 ASP.Net MVC 中将单选按钮与模型数据绑定? [英] How can I bind a radio button with model data in ASP.Net MVC?

查看:19
本文介绍了如何在 ASP.Net MVC 中将单选按钮与模型数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的表单中显示一个单选按钮,该按钮将从模型数据中填充.

这是我的模型

公开课学生{[Required(ErrorMessage = "First Name Required")]//文本框将显示[显示(名称 =名字:")][StringLength(5, ErrorMessage = "名字不能超过 5 个字符.")]公共字符串名字{获取;放;}[Required(ErrorMessage = "Last Name Required")]//文本框将显示[显示(名称 =姓氏:")][StringLength(5, ErrorMessage = "姓氏不能超过 5 个字符.")]公共字符串姓氏 { 获取;放;}[Required(ErrorMessage = "Sex Required")]//显示单选按钮组[显示(名称 =性别:")]公开列表<性别>性别{得到;放;}}公开课性{公共字符串 ID { 获取;放;}公共字符串类型{获取;放;}}

在这里,我试图从像

这样的操作方法手动填充学生模型

public ActionResult Index(){var 学生 = 新学生{FirstName = "Rion",姓氏 = "戈麦斯",性别=新列表<性别>{new Sex{ID="1" , Type = "Male"},new Sex{ID="2" , Type = "Female"}}}返回视图(学生);}

现在我怎样才能生成一个单选按钮,该按钮将以男性 & 形式显示文本女性和作为值将有ID

我在谷歌上搜索并找到了很多样本​​,我使用了一个,但不确定它是否有效.这是视图中的单选按钮代码.

@Html.RadioButtonFor(x => x.Sex, "男")

我不想硬编码男性或女性;我想通过模型展示它,并想在 for 循环中生成单选按钮.

我也是 MVC 新手,所以请指导我.

解决方案

如果我理解正确,您应该更改您的 Student 模型,以便将属性Sex"设为整数,然后您应该拥有另一个名为SexList"的属性填充列表的位置.此更改将允许您发布数据并检索用户选择的性别.

如果您使用 Razor 视图引擎,您应该执行以下操作:

@{foreach(Model.SexList 中的 var 性别){<div>@Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID })@Html.Label("sex" + sex.ID, sex.Type)

}}

你的模型应该是这样的:

公开课学生{[Required(ErrorMessage = "First Name Required")]//文本框将显示[显示(名称 =名字:")][StringLength(5, ErrorMessage = "名字不能超过 5 个字符.")]公共字符串名字{获取;放;}[Required(ErrorMessage = "Last Name Required")]//文本框将显示[显示(名称 =姓氏:")][StringLength(5, ErrorMessage = "姓氏不能超过 5 个字符.")]公共字符串姓氏 { 获取;放;}[必需(ErrorMessage =需要性别")][显示(名称 =性别:")]公共性别{得到;放;}公开列表<性别>SexList { 获取;放;}}公开课性{公共字符串 ID {get;set;}公共字符串类型 {get;set;}}

您在控制器中的操作:

[HttpGet]公共 ActionResult 索引(){var 学生 = 新学生{FirstName = "Rion",姓氏 = "戈麦斯",//我认为填充此列表的最佳方法是在此处调用服务.SexList = 新列表{new Sex{ID="1" , Type = "Male"},new Sex{ID="2" , Type = "Female"}}}返回视图(学生);}

和视图:

@Html.BeginForm(){<div>@Html.LabelFor(model =>model.FirstName)@Html.EditorFor(model => model.FirstName)@Html.ValidationMessageFor(model =>model.FirstName)

<div>@Html.LabelFor(model => model.LastName)@Html.EditorFor(model => model.LastName)@Html.ValidationMessageFor(model =>model.LastName)

@{foreach(Model.SexList 中的 var 性别){<div>@Html.RadioButtonFor(model => model.Gender, new { id = "sex" + sex.ID })@Html.Label("sex" + sex.ID, sex.Type)

}}<input type="submit" value"Submit"/>}

并且您应该以这种方式在控制器中执行操作.这是提交将要发布数据的地方:

[HttpPost]公共 ActionResult 索引(学生模型){如果(模型状态.IsValid){//TODO: 保存模型并重定向}//调用相同的服务再次初始化您的模型(因为我们没有发布性别列表)返回视图(模型);}

I want to show a radio button in my form which will be populated from model data.

here is my model

public class Student
    {
        [Required(ErrorMessage = "First Name Required")] // textboxes will show
        [Display(Name = "First Name :")]
        [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
        public string FirstName { get; set; }

[Required(ErrorMessage = "Last Name Required")] // textboxes will show
        [Display(Name = "Last Name :")]
        [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
        public string LastName { get; set; }

[Required(ErrorMessage = "Sex Required")] // group of radio button will show
        [Display(Name = "Sex :")]
        public List<Sex> Sex { get; set; }

}

public class Sex
    {
        public string ID { get; set; }
        public string Type { get; set; }
    }

here I am trying to populate the student model manually from an action method like

public ActionResult Index()
{
var student=  new Student 
{
    FirstName = "Rion",
    LastName = "Gomes",

    Sex= new List<Sex>
        {
            new Sex{ID="1" , Type = "Male"}, 
            new Sex{ID="2" , Type = "Female"}
        }    
}    
    return View(student);
}

now how could I generate a radio button which will display text in form Male & Female and as value will have the ID

I searched google and found many samples and I used one but not sure if it works. here is the radio button code in view.

@Html.RadioButtonFor(x => x.Sex, "Male")

I do not want to hard code male or female rather; I want to show it through a model and want to generate the radio button in a for loop.

I am new too MVC, so please guide me.

解决方案

If I understood correctly you should change your Student model in order to have the property "Sex" as an integer and then you should have another property called "SexList" where you populate the list. This change will allow you to post your data and retrieve the sex selected by the user.

If you are using Razor view engine you should do something like this:

@{ 
    foreach (var sex in Model.SexList)
    {
        <div>
            @Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID })
            @Html.Label("sex" + sex.ID, sex.Type)
        </div>
    }
}

Edit:

Your model should be something like this:

public class Student
{
    [Required(ErrorMessage = "First Name Required")] // textboxes will show
    [Display(Name = "First Name :")]
    [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name Required")] // textboxes will show
    [Display(Name = "Last Name :")]
    [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Sex Required")]
    [Display(Name = "Sex :")]
    public Sex Gender { get; set; }

    public List<Sex> SexList { get; set; }

}

public class Sex
{
    public string ID {get;set;}
    public string Type {get;set;}
}

Your action in the controller:

[HttpGet]
public ActionResult Index()
{
    var student = new Student 
    {
        FirstName = "Rion",
        LastName = "Gomes",

        //I think the best way to populate this list is to call a service here.
        SexList = new List<Sex>
        {
            new Sex{ID="1" , Type = "Male"}, 
            new Sex{ID="2" , Type = "Female"}
        }    
    }    

    return View(student);
}

And the View:

@Html.BeginForm()
{
    <div>
        @Html.LabelFor(model => model.FirstName)
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
    <div>
        @Html.LabelFor(model => model.LastName)
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>
    @{ 
        foreach (var sex in Model.SexList)
        {
            <div>
                @Html.RadioButtonFor(model => model.Gender, new { id = "sex" + sex.ID })
                @Html.Label("sex" + sex.ID, sex.Type)
            </div>
        }
    }

    <input type="submit" value"Submit" />
}

and you should have an action in your controller this way. This is the place where the submit is going to post the data:

[HttpPost]
public ActionResult Index(Student model)
{
    if (ModelState.IsValid)
    {
        //TODO: Save your model and redirect 
    }

    //Call the same service to initialize your model again (cause we didn't post the list of sexes)
    return View(model);
}

这篇关于如何在 ASP.Net MVC 中将单选按钮与模型数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆