Topic: Selected item is not choose in dropdownlist
I'm learning mvc and have a problem.
I have made a Edit view, when using a @HtmlEditorFor the gender sais either Male or Female. But when using a DropDownList it's sais select Gender.
What do I miss in the code, so the value for Gender is the selected from the db?
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownList("Gender", new List { new SelectListItem{ Text = "Male", Value="Male"}, new SelectListItem{ Text = "Female", Value="Female"} }, "select Gender" ) @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
PARTH
Try below code -
list = new List {
Controller/ Action Method / Model:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Mvc.Controllers
{
public class HomeController : Controller
{
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
List
new Gender { Text = "Male", Value="Male" },
new Gender { Text = "Female", Value="Female" }
};
string selectedValue = "Female";
ViewBag.Gender = new SelectList(list, "Value", "Text", selectedValue);
return View();
}
}
public class Gender
{
public string Text { get; set; }
public string Value { get; set; }
}
}
View:-
@{
ViewBag.Title = "Contact";
}
@ViewBag.Title.
@ViewBag.Message
@Html.DropDownList("Gender", null,
htmlAttributes: new { @class = "form-control" })