简体   繁体   English

为什么我在mvc中的下拉列表中的项目没有被标记为选中状态?

[英]Why don't the items from my dropdownlists in mvc get marked as selected?

I'm using SelectLists to populate the following DropDownLists from the respective models. 我正在使用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>

Here's how it's populated: 填充方式如下:

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;
}

I'm simply adding this to the model by calling model.CompaniesList = GetCompaniesList(CompanyModel.GetCompanies()) . 我只是通过调用model.CompaniesList = GetCompaniesList(CompanyModel.GetCompanies())将其添加到模型中。

These lists render markup that looks like this: 这些列表呈现如下所示的标记:

<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>

I manually wrote in the default value which is pre-selected. 我手动输入了预先选择的默认值。

My problem is that I can't seem to get the selected flag to move over to whichever item I'm selecting. 我的问题是我似乎无法将所选标志移到我选择的任何项目上。 As such, when it comes time to post to the controller, the selected values for these fields come up empty and throw an exception. 这样,当需要发布到控制器时,这些字段的选定值将显示为空并引发异常。

How can I get the dropdownlists to accept my selection and send the data along with the rest of the form in the ajax post? 如何获得下拉列表以接受我的选择,并将数据与表单的其余部分一起发送到ajax帖子中?

EDIT 编辑

Here's my [HttpPost] Add ActionResult (it's a bit of a mess, but that's just some nasty data design on my part which I'll fix up later... 这是我的[HttpPost] Add 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
  }
}

EDIT 2 编辑2

Here's the Model. 这是模型。 A fair amount of inheritance is used here to provide common user values (email address, password) from a framework I'm writing. 这里使用大量的继承来提供我正在编写的框架中的公共用户值(电子邮件地址,密码)。

NOTE: Until I tried to implement the dropdownlists, this all worked just fine. 注意:在我尝试实现下拉列表之前,这一切都很好。

UserModel : Provides MVC with access to the User object and includes CRUD functions UserModel :向MVC提供对User对象的访问,并包括CRUD函数

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

    // CRUDs go here
}

User : Provide application-specific fields (companies, roles) User :提供特定于应用程序的字段(公司,角色)

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

BaseUser : Provides user-common fields (email address, password) 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 : Provides globally common fields to the database tables (primary key, auditing) 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;
    }
}

I always use the "for" helper in this situation 在这种情况下,我总是使用“ for”助手

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

to pre set the selected you just need to set "selectedCompany" on the controller 要预先设置所选内容,您只需在控制器上设置“ selectedCompany”

model.selectedCompany = //the users previous selection

this will also tie the selection made by the user to your model so if the drop down is changed, the value of selectedCompany will be set to what it was changed to on the view. 这还将把用户所做的选择与您的模型联系在一起,因此,如果下拉列表发生更改,则selectedCompany的值将设置为视图中更改后的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM