某人認爲下拉列表的呈現形式不如單選按鈕漂亮,我只好去測試一下單選按鈕與下拉框了。測試代碼以下:html
1.model類Blog.cs(類型使用枚舉類型,自動生成的視圖會如下拉列表形式顯示):java
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 生成解決方案,而後新建帶視圖的控制器。python
3.修改自動生成的Create.cshtml視圖代碼以下(仔細看一下更改部分):mysql
<div class="form-group"> @Html.LabelFor(model => model.B_Type, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EnumDropDownListFor(model => model.B_Type, htmlAttributes: new { @class = "form-control" })</span> @Html.ValidationMessageFor(model => model.B_Type, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.B_Tag, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @*@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</span> @Html.ValidationMessageFor(model => model.B_Tag, "", new { @class = "text-danger" }) </div> </div>
4.在瀏覽器打開Create.cshtml視圖,新建一條數據,系統在自動建立數據庫時會往數據庫添加你新建的數據內容web
5.修改Edit.cshtml視圖代碼以下(注意觀察不一樣,視圖呈現時會自動選中數據庫存儲的內容的):sql
<div class="form-group"> @Html.LabelFor(model => model.B_Tag, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @*@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</span> @Html.RadioButtonFor(model => model.B_Tag, "python", new { htmlAttributes = new { @class = "form-control" } })Python @Html.ValidationMessageFor(model => model.B_Tag, "", new { @class = "text-danger" }) </div> </div>
6.若是你作了一遍,就會對流程比較清楚了,對應着改本身的項目便可。如今我仍是分不清哪一個漂亮,不過從實現上講,下拉列表更易實現,只需將model類中的某一字段定義爲枚舉類型,就沒必要你改代碼了呀。數據庫