【问题标题】:Default Value for DropDownList COntrols on ASP.NET MVC [duplicate]ASP.NET MVC 上 DropDownList 控件的默认值 [重复]
【发布时间】:2018-11-24 02:22:02
【问题描述】:

我是 MVC 新手(数据库优先),我有一个问题 我有一个带有 DropDownList 控件的表单。 DropDownList 控件已绑定到数据库上的列,但我希望将默认值作为项目的一部分,例如“--selectgrade--” 我该怎么做? 我有几个从脚手架生成的视图和控制器。

我将为特定对象附加我的视图以及我的控制器。 DropDownLists @Html.DropDownList("StudentID", null, htmlAttributes: new { @class= "form-control" })

@Html.DropDownList("CourseID", null, htmlAttributes: new { @class= "form-control" })

有什么问题

@model ContosoSite.Models.Enrollment

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>Enrollment</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Grade, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Grade, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Grade, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
    @Html.LabelFor(model => model.CourseID, "CourseID", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("CourseID", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CourseID, "", new { @class = "text-danger" })
    </div>
</div>



    <div class="form-group">
        @Html.LabelFor(model => model.StudentID, "StudentID", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("StudentID", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.StudentID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ContosoSite.Models;

namespace ContosoSite.Controllers
{
    public class EnrollmentsController : Controller
    {
        private ContosoUniversityEntities db = new ContosoUniversityEntities();

        // GET: Enrollments
        public ActionResult Index()
        {
            var enrollments = db.Enrollments.Include(e => e.Course).Include(e => e.Student);
            return View(enrollments.ToList());
        }

        // GET: Enrollments/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            return View(enrollment);
        }

        // GET: Enrollments/Create
        public ActionResult Create()
        {
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title");
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName");
            return View();
        }

        // POST: Enrollments/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "EnrollmentID,Grade,CourseID,StudentID")] Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                db.Enrollments.Add(enrollment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
            return View(enrollment);
        }

        // GET: Enrollments/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
            return View(enrollment);
        }

        // POST: Enrollments/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "EnrollmentID,Grade,CourseID,StudentID")] Enrollment enrollment)
        {
            if (ModelState.IsValid)
            {
                db.Entry(enrollment).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CourseID = new SelectList(db.Courses, "CourseID", "Title", enrollment.CourseID);
            ViewBag.StudentID = new SelectList(db.Students, "StudentID", "LastName", enrollment.StudentID);
            return View(enrollment);
        }

        // GET: Enrollments/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Enrollment enrollment = db.Enrollments.Find(id);
            if (enrollment == null)
            {
                return HttpNotFound();
            }
            return View(enrollment);
        }

        // POST: Enrollments/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Enrollment enrollment = db.Enrollments.Find(id);
            db.Enrollments.Remove(enrollment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

【问题讨论】:

  • 此方法有一个重载,它采用选项标签。使用它。

标签: asp.net-mvc html.dropdownlistfor


【解决方案1】:

剃刀视图:

@Html.DropDownList("StudentGender", 
                new SelectList(Enum.GetValues(typeof(Gender))),
                "Select Gender",
                new { @class = "form-control" })

结果:

<select class="form-control" id="StudentGender" name="StudentGender">
    <option>Select Gender</option> 
    <option>Male</option> 
    <option>Female</option> 
</select>

参考。 http://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

【讨论】:

    【解决方案2】:

    您可以使用 DropDownList 辅助方法的this overload

    public static DropDownList (thisHtmlHelper htmlHelper,
                                string name, 
                                IEnumerable<System.Web.Mvc.SelectListItem> selectList, 
                                string optionLabel,  
                                IDictionary<string,object> htmlAttributes);
    

    这里的第三个参数optionLabel 用于为默认项构建一个选项项。该选项将没有value 属性值。

    所以在你的情况下,你的视图代码将是

    @Html.DropDownList("CourseID", ViewBag.CourseID as SelectList,
                                        "--select grade--",  new { @class = "form-control" })
    

    这将呈现一个 SELECT 元素,其中第一个选项将是“选择等级”并且将被选中(因为它是第一个)。如果您希望选择其他一些选项作为默认选项,请考虑将DropDownListFor 辅助方法与视图模型一起使用。有关该方法的示例代码,请参阅 this post

    【讨论】:

    • 感谢@Shyju,这非常有效。再次感谢!
    猜你喜欢
    • 2017-07-26
    • 2019-12-15
    • 2019-06-05
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2016-07-12
    相关资源
    最近更新 更多