AKD
AKD

Reputation: 3966

Pass select list selected value in model

i have following model class

class Emp
{
    int id { get; set; }
    string name { get; set; }
    Role role { get; set; }
}
class Role
{
    int id { get; set; }
    string rolename { get; set; }
}

and below is my form to perform update entity
.aspx

@using(@Html.BeginForm("edit", "Home", FormMethod.Post)){

            <label>name: </label>@Html.TextBoxFor(m => m.Name)<br />
            <label>role: </label>@Html.DropDownListFor(m => m.Role, (SelectList)ViewBag.roles)

            @Html.Hidden("empid", Model.EmpId)

            <input type="submit" value="submit" />
        }

C# Action Method

public ActionResult edit(Emp emp)
{
      if (ModelState.IsValid) // <-- always returning false
      {
          // Model.Role getting null, why ?
      }
}

To populate dropdown the selectList

ViewBag.roles = new SelectList(dbContext.Roles, "roleid", "rolename", SelectedRole);

now in edit method emp model contains empid and name, but role getting null, any idea ?

Upvotes: 2

Views: 596

Answers (3)

vborutenko
vborutenko

Reputation: 4443

I thinck it should be

ViewBag.roles = new SelectList(dbContext.Roles, "id", "rolename", SelectedRole);

"id" instead of "roleid"

Upvotes: 0

Skye MacMaster
Skye MacMaster

Reputation: 914

There really isn't anything to tell it how to create a Role object from the value of the selected role on the post back. Also, when creating the view, it also has no idea which property of the Role object to use to select an item in the drop down.

So in short you should bind the drop down to a property of type string not a user defined type.

Upvotes: 0

Ashish Charan
Ashish Charan

Reputation: 2387

Probably the reason is that, model binder cannot bind complex types contained in the model. You can possibly get this to work by having a RoleId field in the Emp model and then binding the drop down to that RoleId.

Or you can go for editor templates to achieve intended functionality.

Upvotes: 1

Related Questions