標籤:down log 入門 入門教程 http group ota pac pytho
某人認為下拉式清單的呈現形式不如選項按鈕漂亮,我只好去測試一下選項按鈕與下拉框了。測試代碼如下:
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視圖代碼如下(仔細看一下更改部分):
<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視圖,建立一條資料,系統在自動建立資料庫時會往資料庫添加你建立的資料內容
5.修改Edit.cshtml視圖代碼如下(注意觀察不同,視圖呈現時會自動選中資料庫儲存的內容的):
<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類中的某一欄位定義為枚舉類型,就不必你改代碼了呀。
MVC5使用選項按鈕與下拉框【轉】