0

i am new to MVC (database first), and i have a question I have a form, with a DropDownList control. the DropDownList Control has been bound to a column on a database, but i want to have as part of the items, a default value e.g "--select grade--" how do i go about this? i have a couple of views and controllers generated from scaffolding.

i will attach my view as well as my controller for the particular object. DropDownLists @Html.DropDownList("StudentID", null, htmlAttributes: new { @class = "form-control" })

and

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

are the concerns

@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);
        }
    }
}
uchenna
  • 1
  • 3

2 Answers2

0

Razor view:

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

Result:

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

Ref. http://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

Wing Kui Tsoi
  • 474
  • 1
  • 6
  • 16
0

You can use this overload of the DropDownList helper method.

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

Here the third parameter optionLabel is used to build the an option item for for the default item. The option will not have a value attribute value.

So in your case, your view code will be

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

This will render a SELECT element where the first option will be "select grade" and that will be selected (because it is first). If you want some other option item to be selected as default, consider using the DropDownListFor helper method with a view model. Refer this post for sample code on that approach.

Shyju
  • 214,206
  • 104
  • 411
  • 497