ASP.NET MVC

时间:2018-11-23 18:07:07

标签: asp.net-mvc html.dropdownlistfor

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

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

@ Html.DropDownList(“ CourseID”,null,htmlAttributes:新的{@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);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

剃刀视图:

@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

答案 1 :(得分:0)

您可以使用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元素,其中第一个选项将是“ select grade”,并且将被选中(因为它是第一个)。如果您希望将其他选项项选为默认选项,请考虑对视图模型使用DropDownListFor帮助方法。有关该方法的示例代码,请参见this post