I recently posted a question about the html helper dropdown and got it working ( here ). But now I decided it was a lot smarter to switch to ModelView Templates, so I have access to strongly typed methods in my views, etc. I made some code changes in my other topic as follows:
VacatureFormViewModel:
public class VacaturesFormViewModel
{
public Vacatures Vacature { get; private set; }
public SelectList EducationLevels { get; private set; }
public SelectList Branches { get; private set; }
public SelectList CareerLevels { get; private set; }
Repository repository;
public VacaturesFormViewModel(Vacatures vacature)
{
this.Vacature = vacature;
this.repository = new Repository();
this.EducationLevels = new SelectList(repository.GetAllEducationLevels(),"ID","Name",vacature.EducationLevels);
this.Branches = new SelectList(repository.GetAllBranches(),"ID","Name",vacature.Branches);
this.CareerLevels = new SelectList(repository.GetAllCareerLevels(), "ID", "Name", vacature.CareerLevels);
}
}
BanenController:
public ActionResult Create()
{
Vacatures vacature = new Vacatures();
return View(new VacaturesFormViewModel(vacature));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Vacatures vacatureToAdd)
{
if (ModelState.IsValid)
{
try
{
repository.AddToVacatures(vacatureToAdd);
repository.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
return View();
}
}
}
And my view of Create.aspx (part of it):
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Title">Title:</label>
<%= Html.TextBox("Title", Model.Vacature.Title) %>
<%= Html.ValidationMessage("Title", "*") %>
</p>
<p>
<label for="Content">Content:</label>
<%= Html.TextArea("Content", Model.Vacature.Content) %>
<%= Html.ValidationMessage("Content", "*") %>
</p>
<p>
<label for="EducationLevels">EducationLevels:</label>
<%= Html.DropDownList("EducationLevels", Model.EducationLevels)%>
<%= Html.ValidationMessage("EducationLevels", "*") %>
</p>
<p>
<label for="CareerLevels">CareerLevels:</label>
<%= Html.DropDownList("CareerLevels", Model.CareerLevels)%>
<%= Html.ValidationMessage("CareerLevels", "*")%>
</p>
<p>
<label for="Branches">Branches:</label>
<%= Html.DropDownList("Branches", Model.Branches)%>
<%= Html.ValidationMessage("Branches", "*")%>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
For guidance I used NerdDinner from ScottGu and here I read various topics.
, , MVC ASP , (dropdownlists), , , . SelectList :
this.CareerLevels = new SelectList(repository.GetAllCareerLevels(), vacature.CareerLevels);
, "" "" ( , - post, ), : vacature.EducationLevels .. , , .
, , , , . ?
, :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection form)
{
Vacatures vacatureToAdd = new Vacatures();
if (!form["EducationLevels"].Equals(""))
{
Guid educationID = new Guid(form["EducationLevels"]);
vacatureToAdd.EducationLevels = repository.GetEducationLevelByID(educationID);
}
? , .