Reading from here: ASP.NET MVC
Action SelectCategory
has been created inside controller -
public ActionResult SelectCategory() {
while binding you list to DropDown you need to type cast it to IEnumerable as you use @Html.DropDown control which is not strongly type with Model
In View
@Html.DropDownList("MovieType",(IEnumerable<SelectListItem>)ViewBag.MovieType)
and for another way if you bind IdList then
@Html.DropDownList("IdList",(IEnumerable<SelectListItem>)ViewBag.IdList)
You have set ViewBag.MovieType
=> when you use @Html.DropDownList("MovieType")
the dropdown will use this value. When you write @Html.DropDownList("IdList")
, the helper doesn't find a corresponding IdList
property in ViewBag and throws an error because it doesn't know from where to bind the data.
Alternatively if you want to change the name of the dropdown you could use the following:
@Html.DropDownList("SelectedMovieType", (IEnumerable<SelectListItem>)ViewBag.MovieType)
and your POST action will have a SelectedMovieType
parameter to retrieve the selected value.
But I would avoid ViewBag. Defining a view model is better:
public class MyViewModel
{
public string SelectedMovieType { get; set; }
public IEnumerable<SelectListItem> MovieTypes { get; set; }
}
and then have your controller action populate this view model and pass it to the view:
public ActionResult SelectId()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "MyId1", Value = "MyId1", Selected=true });
items.Add(new SelectListItem { Text = "MyId2", Value = "MyId2" });
var model = new MyViewModel
{
MovieTypes = items
};
return View(model);
}
and in your strongly typed view:
@model MyViewModel
@Html.DropDownListFor(x => x.SelectedMovieType, Model.MovieTypes)
A painless way for data binding to bind data to the model: Do not use the razor for Dropdown. Bind it manually, get it with FormCollection object.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Sorun sorun,FormCollection fc)
{
//Define independently as form collection
sorun.GonderilecekBirim = fc["GonderilecekBirim"];
sorun.IlkSorulmaTarihi = DateTime.Now;
if (ModelState.IsValid)
{
db.Soruns.Add(sorun);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(sorun);
}
View
@Html.LabelFor(model => model.GonderilecekBirim, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<!-- Define as raw html -->
<select id="GonderilecekBirim" name="GonderilecekBirim">
<option value="4">Satın Alma</option>
<option value="5">Muhasebe</option>
</select>
@*@Html.ValidationMessageFor(model => model.GonderilecekBirim, "", new { @class = "text-danger" })*@
</div>