0

Recently I posted a question about the html helper dropdownlist and got it working (here). But now I have decided it was alot smarter to switch to ModelView Patterns so I have acces to strongly typed methods in my views etc. What I did was I made some adjustments to the code in my other topic in the following way:

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;

    // Constructor
    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:

//
    // GET: /Banen/Create

    public ActionResult Create()
    {
        Vacatures vacature = new Vacatures();
        return View(new VacaturesFormViewModel(vacature));
    }

    //
    // POST: /Banen/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Vacatures vacatureToAdd)
    {
        if (ModelState.IsValid)
        {
            try
            {
                // TODO: Add insert logic here
                repository.AddToVacatures(vacatureToAdd);
                repository.SaveChanges();

                // Return to listing page if succesful
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                return View();
            }
        }
    }

And my Create.aspx view (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 guiding I have used the NerdDinner tutorial by ScottGu and I have read various topics here.

My question is if it is possible to let MVC ASP set my careerlevel, educationlevel and branche (dropdownlists) automatically as it currently is returning an ID string which is not what I want. When I change the creation of the SelectList to:

this.CareerLevels = new SelectList(repository.GetAllCareerLevels(), vacature.CareerLevels);

So without the "ID" and "Name" it does not save either (I guess it is still returned as a string in the post method, and not the object itself) and next to this, it lists in the view as: vacature.EducationLevels etc. So not the Names but the object itself is listed.

Final question So, in short, my question is if it is possible to use this approach to set my branche, educationallevel and careerlevel. So not automatically?

In which case I still have to use things like:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection form)
    {
        Vacatures vacatureToAdd = new Vacatures();

        // Retrieve the education level by its ID
        if (!form["EducationLevels"].Equals(""))
        {
            Guid educationID = new Guid(form["EducationLevels"]);
            vacatureToAdd.EducationLevels = repository.GetEducationLevelByID(educationID);
        }

In my controller? Or are there other, smoother options.

3 Answers 3

2

Edited to use Guid:

With dropdownlists I use a slightly different approach. It might be possible to get your viewmodel working, but for me it is easier this way:

public class VacaturesFormViewModel
{

    public IEnumerable<SelectListItem>EducationLevels{ get; set; }
    public Guid EducationLevelID{ get; set; }

}

The EducationLevelID will have the selected id of your Dropdown. This is the view:

<%= Html.DropDownList("EducationLevelID", Model.EducationLevels)%>

Controller

  IEnumerable<SelectListItem> educationLevelList =
                            from level in GetLevelList()
                            select new SelectListItem
                            {
                                Text = level .Name,
                                Value = level.Uid.ToString()
                            };
  model.EducationLevels = educationLevelList ;
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that I that my EducationLevelID is not an int (as is supported by dropdownlist?) but a GUID which is not supported at once. You have to generate the GUID from the return of the dropdownlist yourself as far as I know. Which means I still have to do the steps I did before.
I checked and the Guid is not a problem. The edited code uses IEnumerable<SelectListItem> but there should be no differnce to SelectList
so, how is the dropdownlist using 'EducationLevelID' to show the selected item appropriately?
1

I'm not for sure but I think you should create model binders. (David Hayden wrote an simple model binder)

2 Comments

This is also an example of string based information only. As he uses: HttpContext.Request.Form["Name"]; Which is exactly what goes wrong in my case, that does not give an object I think, but rather a string. Not sure though.
On second hand, this might actually work as: > Blockquote "You can create your own Custom Model Binders for Customer that instantiates a new Customer Instance and adds the appropriate form values to the various Customer Properties" sounds promising.
1

You could bind educationID parameter automatically:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Guid? educationID, FormCollection form)
{
    Vacatures vacatureToAdd = new Vacatures();

    if (educationID != null)
    {
        vacatureToAdd.EducationLevels = 
            repository.GetEducationLevelByID(educationID.Value);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.