MVC5使用单选按钮与下拉框

某人认为下拉列表的呈现形式不如单选按钮漂亮,我只好去测试一下单选按钮与下拉框了。测试代码如下:

1.model类Blog.cs(类型使用枚举类型,自动生成的视图会以下拉列表形式显示):

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace WebTest.Models
{
    public enum B_Type
    {
        原创,转载,翻译
    }
    public class Blog
    {
        [Key] 
        public int B_Id { get; set; }
        
        [DisplayName("标题")]
        public string B_Title { get; set; }

        [DisplayName("内容")]
        public string B_Content { get; set; } 
        
        [DisplayName("类型")]
        public B_Type B_Type { get; set; }

        [DisplayName("标签")]
        public string B_Tag { get; set; }
    }
}


2.在web.config添加连接数据库的字符串(推荐使用sql server数据库,或者使用vs自带的localdb。这一步不会就乖乖去看入门教程,懒得写步骤),然后快捷键ctrl+shift+B 生成解决方案,然后新建带视图的控制器。

3.修改自动生成的Create.cshtml视图代码如下(仔细看一下更改部分):

  
@Html.LabelFor(model => model.B_Type, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EnumDropDownListFor(model => model.B_Type, htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.B_Type, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.B_Tag, htmlAttributes: new { @class = "control-label col-md-2" })
@*@Html.EditorFor(model => model.B_Tag, new { htmlAttributes = new { @class = "form-control" } })*@ @Html.RadioButtonFor(model=>model.B_Tag, "c#",new { htmlAttributes = new { @class = "form-control" } })C# @Html.RadioButtonFor(model => model.B_Tag, "java", new { htmlAttributes = new { @class = "form-control" } })Java @Html.RadioButtonFor(model => model.B_Tag, "python", new { htmlAttributes = new { @class = "form-control" } })Python @Html.ValidationMessageFor(model => model.B_Tag, "", new { @class = "text-danger" })

4.在浏览器打开Create.cshtml视图,新建一条数据,系统在自动创建数据库时会往数据库添加你新建的数据内容

5.修改Edit.cshtml视图代码如下(注意观察不同,视图呈现时会自动选中数据库存储的内容的):

        
@Html.LabelFor(model => model.B_Tag, htmlAttributes: new { @class = "control-label col-md-2" })
@*@Html.EditorFor(model => model.B_Tag, new { htmlAttributes = new { @class = "form-control" } })*@ @Html.RadioButtonFor(model => model.B_Tag, "c#", new { htmlAttributes = new { @class = "form-control" } })C# @Html.RadioButtonFor(model => model.B_Tag, "java", new { htmlAttributes = new { @class = "form-control" } })Java @Html.RadioButtonFor(model => model.B_Tag, "python", new { htmlAttributes = new { @class = "form-control" } })Python @Html.ValidationMessageFor(model => model.B_Tag, "", new { @class = "text-danger" })
6.如果你做了一遍,就会对流程比较清楚了,对应着改自己的项目即可。现在我还是分不清哪个漂亮,不过从实现上讲,下拉列表更易实现,只需将model类中的某一字段定义为枚举类型,就不必你改代码了呀。



你可能感兴趣的:(.net平台,mvc,单选按钮)