Default Value for DropDownList COntrols on ASP.NET MVC [duplicate]












0
















This question already has an answer here:




  • mvc 5 SelectList from table with blank value for DropDownList

    4 answers




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);
}
}
}












share|improve this question













marked as duplicate by user3559349 Nov 23 '18 at 20:25


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.



















  • There is an overload of this method which takes an option label. Use that.

    – Shyju
    Nov 23 '18 at 18:08
















0
















This question already has an answer here:




  • mvc 5 SelectList from table with blank value for DropDownList

    4 answers




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);
}
}
}












share|improve this question













marked as duplicate by user3559349 Nov 23 '18 at 20:25


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.



















  • There is an overload of this method which takes an option label. Use that.

    – Shyju
    Nov 23 '18 at 18:08














0












0








0









This question already has an answer here:




  • mvc 5 SelectList from table with blank value for DropDownList

    4 answers




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);
}
}
}












share|improve this question















This question already has an answer here:




  • mvc 5 SelectList from table with blank value for DropDownList

    4 answers




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);
}
}
}







This question already has an answer here:




  • mvc 5 SelectList from table with blank value for DropDownList

    4 answers







@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")
}





@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);
}
}
}





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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 18:07









uchennauchenna

11




11




marked as duplicate by user3559349 Nov 23 '18 at 20:25


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by user3559349 Nov 23 '18 at 20:25


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • There is an overload of this method which takes an option label. Use that.

    – Shyju
    Nov 23 '18 at 18:08



















  • There is an overload of this method which takes an option label. Use that.

    – Shyju
    Nov 23 '18 at 18:08

















There is an overload of this method which takes an option label. Use that.

– Shyju
Nov 23 '18 at 18:08





There is an overload of this method which takes an option label. Use that.

– Shyju
Nov 23 '18 at 18:08












2 Answers
2






active

oldest

votes


















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






share|improve this answer































    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.






    share|improve this answer


























    • thanks @Shyju this worked perfectly. thanks once again!

      – uchenna
      Nov 25 '18 at 19:32


















    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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






    share|improve this answer




























      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






      share|improve this answer


























        0












        0








        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






        share|improve this answer













        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







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 18:14









        Wing Kui TsoiWing Kui Tsoi

        15612




        15612

























            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.






            share|improve this answer


























            • thanks @Shyju this worked perfectly. thanks once again!

              – uchenna
              Nov 25 '18 at 19:32
















            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.






            share|improve this answer


























            • thanks @Shyju this worked perfectly. thanks once again!

              – uchenna
              Nov 25 '18 at 19:32














            0












            0








            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.






            share|improve this answer















            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.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 23 '18 at 18:22

























            answered Nov 23 '18 at 18:15









            ShyjuShyju

            145k87331438




            145k87331438













            • thanks @Shyju this worked perfectly. thanks once again!

              – uchenna
              Nov 25 '18 at 19:32



















            • thanks @Shyju this worked perfectly. thanks once again!

              – uchenna
              Nov 25 '18 at 19:32

















            thanks @Shyju this worked perfectly. thanks once again!

            – uchenna
            Nov 25 '18 at 19:32





            thanks @Shyju this worked perfectly. thanks once again!

            – uchenna
            Nov 25 '18 at 19:32



            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'