为什么不将mvc中的下拉列表中的项目标记为已选中?

时间:2015-01-27 09:36:07

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我使用SelectLists从相应的模型中填充以下DropDownLists。

<div class="editor-field">
    @Html.DropDownList("Companies", Model.Companies)
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.Role, "User Role")
</div>
<div class="editor-field">
    @Html.DropDownList("Roles", Model.Roles)
</div>

以下是它的填充方式:

public List<SelectListItem> GetCompaniesList(List<Company> Companies)
{
    var list = new List<SelectListItem>();

    foreach (Company comp in Companies)
    {
        var item = new SelectListItem { Text = comp.Companyname, Value = Convert.ToString(comp.PKey) };
        list.Add(item);
    }

    return list;
}

我只需通过调用model.CompaniesList = GetCompaniesList(CompanyModel.GetCompanies())将其添加到模型中。

这些列表呈现如下所示的标记:

<select id="ddlRoles" name="ddlRoles" class="valid">
    <option selected="selected" value="0">Please select a Role</option>
    <option value="2">Admin</option>
    <option value="1">Master</option>
    <option value="3">User</option>
</select>

我手动写入了预先选择的默认值。

我的问题是,我似乎无法将所选标志移到我选择的任何项目上。因此,当需要发布到控制器时,这些字段的选定值将变为空并引发异常。

如何让下拉列表接受我的选择并将数据与ajax帖子中的其余表单一起发送?

编辑

这里是我的[HttpPost]添加ActionResult(它有点混乱,但这只是我个人讨厌的数据设计,我稍后会解决这个问题。

[HttpPost]
public ActionResult Add(UserModel model)
{
  // this check fails saying that Companies and Roles don't have values
  if (ModelState.IsValid)
  {
    try
    {
      // these fields are for auditing
      model.CreatedBy = String.Format("{0} {1}", Convert.ToString(Session["firstname"]), Convert.ToString(Session["lastname"]));
      model.CreatedOn = DateTime.Now;
      // get the selected values from the dropdownlists
      Int64 companyid = Convert.ToInt64(model.Companies.Single(x => x.Selected).Value);
      Int64 role = Convert.ToInt64(model.Roles.Single(x => x.Selected).Value);   
      // the UserModel accepts a User object to add to the database,
      // so copy the model's values over to the user object for adding.
      // this is a lot of the mess which will be cleaned up later
      User u = new User();
      WebCompany c = new WebCompany();
      WebRole r = new WebRole();
      u.Company = c.GetCompanyById(companyid);
      u.Role = r.GetRoleById(role);
      u.CreatedBy = model.CreatedBy;
      u.CreatedOn = model.CreatedOn;
      u.EmailAddress = model.EmailAddress;
      u.FirstName = model.FirstName;
      u.LastName = model.LastName;
      u.LastLogin = model.LastLogin;
      u.Password = model.Password;
      model.Add(u);
      return Json(new
      {
        Message = "Success",
        IsOK = bool.TrueString
      });
    }
    catch (Exception ex)
    {
      if (Request.IsAjaxRequest())
      {
        return ThrowError(ex, "Add");
      }
      else
      {
        return View("Index");
      }
    }
  }
  else
  {
    // return a Json that contains information about why the model is invalid
  }
}

编辑2

这是模特。这里使用了大量的继承来提供我写的框架中的常用用户值(电子邮件地址,密码)。

注意:在我尝试实施下拉列表之前,这一切都运行得很好。

UserModel:为MVC提供对User对象的访问权限,并包含CRUD函数

public class UserModel : User
{
    public List<SelectListItem> Companies { get; set; }
    public List<SelectListItem> Roles { get; set; }

    // CRUDs go here
}

User:提供特定于应用程序的字段(公司,角色)

public class User : BaseUser
{
    public virtual Company Company { get; set; }
    public virtual Role Role { get; set; }
    public DateTime? LastLogin { get; set; }
}

BaseUser:提供用户公共字段(电子邮件地址,密码)

public abstract class BaseUser : BaseObject
{
    public string EmailAddress { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public BaseUser()
    {
        EmailAddress = String.Empty;
        Password = String.Empty;
        FirstName = String.Empty;
        LastName = String.Empty;
    }        
}

BaseObject:为数据库表提供全局公共字段(主键,审计)

public abstract class BaseObject
{
    [Key]
    public Int64 PKey { get; set; }
    public string CreatedBy { get; set; }
    public DateTime CreatedOn { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedOn { get; set; }

    public BaseObject()
    {
        CreatedBy = "System";
        CreatedOn = DateTime.Now;

        ModifiedBy = "System";
        ModifiedOn = DateTime.Now;
    }
}

1 个答案:

答案 0 :(得分:0)

我总是使用&#34; for&#34;这种情况下的助手

@Html.DropDownListFor(x => x.selectedCompany, Model.Companies)

预先设定所选的你只需要设置&#34; selectedCompany&#34;在控制器上

model.selectedCompany = //the users previous selection

这也会将用户所做的选择与您的模型联系起来,因此如果更改下拉列表,selectedCompany的值将设置为视图中更改的值。