ASP MVC3 get and set dropdown list items

I am trying to populate an ASP MVC3 dropdown list with only two selectable items and determine which item to select based on the value in the database. So far this is what I have in my view (which I believe is correct)

    <div class="editor-label">
        @Html.LabelFor(model => model.Status)
    </div>
    <div class="editor-field">
        @Html.DropDownList("CategoryID")
    </div>

      

But I am facing the problem of getting and setting values ​​in the controller.

First, the method I am using appears to only select the value in the combobox that is specified first SelectListItem

.

    public ActionResult Edit(int id)
    {
        //redirect if security is not met.  Must be admin here
        if (!Security.IsAdmin(User)) return RedirectToAction("Message", "Home", new { id = 1 });

        var item = db.FollowUpItems.Find(id);

        string start = string.Empty;

        if (item.Status.Equals("O")) start = "Open";
        else start = "Closed";

        ViewBag.CategoryID = new SelectList(new[]
                                                {
                                                    new SelectListItem {Text = "O", Value = "Open"},
                                                    new SelectListItem {Text = "C", Value = "Closed"},
                                                },"Text", "Value", start);

        FollowUpItems followupitems = db.FollowUpItems.Find(id);
        return View(followupitems);
    }

      

Secondly, when I click a button Save

on the edit page, the Status

element property FollowUpItem

that is passed to that part of the controller is always zero.

    [HttpPost]
    public ActionResult Edit(FollowUpItems followupitems)
    {
        try
        {
            if (ModelState.IsValid)
            {
                db.Entry(followupitems).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (DbEntityValidationException dbEx)
        {
            ViewBag.ErrorMessage = Common.ErrorCheck.CombineDbErrors(dbEx);
        }
        catch (Exception ex)
        {
            ViewBag.ErrorMessage = ErrorCheck.FriendlyError(ex);
        }

        return View(followupitems);
    }

      

EDIT

The issue GET

was resolved thanks to Quinton's answer below, however I am still having trouble setting the value. Using the method @Html.DropDownList("CategoryID")

returns a value null

to the controller every time (for the Status value, all others are as they should be) and using the syntax @Html.DropDownListFor(m => m.Status, ViewBag.CategoryID)

gives the following error message:

'Compiler error message: CS1973: "System.Web.Mvc.HtmlHelper" does not have an applicable method named "DropDownListFor" but has an extension method by that name. Extension methods cannot be dispatched dynamically. Consider using dynamic arguments or calling an extension method without the extension method syntax. '

FINAL IMAGE

The following view in my view allowed me to set the values ​​correctly

@Html.DropDownListFor(m => m.Status, (SelectList)ViewBag.CategoryID)

      

+3


source to share


1 answer


Is the item.Status field O

or C

? If so, then it might work, change the method GET

to:

    public ActionResult Edit(int id) {
        //redirect if security is not met.  Must be admin here
        if (!Security.IsAdmin(User)) return RedirectToAction("Message", "Home", new { id = 1 });

        var item = db.FollowUpItems.Find(id);

        //string start = string.Empty;

        //if (item.Status.Equals("O")) start = "Open";
        //else start = "Closed";

        var StatusOptions = new [] { new { Text = "Open", Value = "O" }, new { Text = "Closed", Value = "C" }};
        ViewBag.CategoryID = new SelectList(StatusOptions, "Value", "Text", item.Status);

        /* this line is duplicated 
         */
        // FollowUpItems followupitems = db.FollowUpItems.Find(id);
        return View(item);
    }

      

I don't know what happened to yours @Html.DropDownList("CategoryID")

, you can change it to:

@Html.DropDownListFor(m => m.Status, (SelectList)ViewBag.CategoryID)

      



I use it as I find it more expressive - I can clear which model property I want to bind.

This can fix the model binding issue. Just a side note - before you can set the state of the Entity, you must first bind it to the db context,

db.Set<FollowUpItems>().Attach(followupitems);

      

+4


source







All Articles