0

I want to load a dropdownlist with values received from my mysql database.

This is what I have in my ViewModel:

public int ProjectID { get; set; }
public IEnumerable<SelectListItem> Projects { get; set; }

Create function in my Controller:

public ActionResult Create(DeliverableViewModel model)
    {
        var projects = (repository.GetProjects()).ToList();
        ViewBag.Projects = projects;

        if (ModelState.IsValid)
        {
            try
            {

                repository.AddDeliverable(model.ProjectID);
            }
            catch (ArgumentException ae)
            {
                ModelState.AddModelError("", ae.Message);
            }
            return RedirectToAction("Index");
        }

        return View(model);
    }

I load the projects in my repository. (values: project_id and project_name)

This is my Create View:

    @model GDMfrontEnd.Models.DeliverableViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

    @using (Html.BeginForm("Create", "Deliverable", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)

            <div class="editor-field">
                 @Html.DropDownListFor(model => model.Projects,
       new SelectList(ViewBag.Projects,
        "project_id", "project_name"))
            </div>
            <p>
                <input type="submit" value="Create" />
            </p>

    }

But now, how can I give my ProjectID from the selected value to my repository?

2 Answers 2

4

Assuming:

class DeliverableViewModel 
{
    public int ProjectID { get; set; }
    public IEnumerable<SelectListItem> Projects { get; set; }
}

It should be like that:

@Html.DropDownListFor(model => model.ProjectID,
    new SelectList(Model.Projects, "project_id", "project_name", Model.ProjectID))

You can omit last Model.ProjectID if you don't initialize this field, but you will probably use it in edit.

Sign up to request clarification or add additional context in comments.

Comments

0

It should be model=>model.ProjectID to retrieve selected ProjectID in POST action.

  @Html.DropDownListFor(model => model.ProjectID,
           new SelectList(ViewBag.Projects,
            "project_id", "project_name"))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.