Pass List data along with ViewModel to view and populate list data in drop down

asp.net-mvc asp.net-mvc-viewmodel c# entity-framework

Accepted Answer

Since DropDownList uses IEnumerable<SelectListItem> swap out the view model for

public class CompanyProfileModelView
{
  public Company Company { get; set; }
  public SelectList CategoryList { get; set; } 
}

and supposingCompany model includes

[Display(Name="Category")]
public int? CategoryType { get; set; }

Controller

[HttpGet]
public ActionResult CreateCompany()
{
    var listData = _appFunctions.GetAllCategory();
    var model = new CompanyProfileModelView
    {
      CategoryList = new SelectList(listData, "CategoryTypeID ", "CategoryTitle")
    };
    return View(model);
}

[HttpPost]
public ActionResult CreateCompany(CompanyProfileModelView model)
{
  if (!ModelState.IsValid)
  {
    // Re-assign select list if returning the view
    var listData = _appFunctions.GetAllCategory();
    model.CategoryList = new SelectList(listData, "CategoryTypeID ", "CategoryTitle");
    return View(model)
  }
  // Save and redirect
}

View

@model App.DAL.Model.CompanyProfileModelView
@using (Html.BeginForm()) // Note, no parameters required in this case
{
  ....
  @Html.LabelFor(m => m.Company.CategoryType, new { @class = "control-label col-md-2" })
  @Html.DropDownListFor(m => m.Company.CategoryType, Model.CategoryList, "--Please select--")
  @Html.ValidationMessageFor(m => m.Company.CategoryType)
  .....
  <input type="submit" value="Create" class="btn btn-default" />
}
2
2/9/2015 9:27:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow