【问题标题】:DropdownListFor doesn't show the selected valueDropdownListFor 不显示所选值
【发布时间】:2016-04-01 12:01:04
【问题描述】:

我很困惑如何使下拉列表显示所选值。

型号:

public class SampleModel
{        
    public string State { get; set; }
}

控制器:

public ActionResult EditInformation()
{
    ViewBag.State = new SelectList(db.States, "StateName", "StateName");

    string userEmail = User.Identity.GetUserName();

    Sample model = new SampleModel();     
    model.State = "Melbourne";

    return View(model);
}

查看:

@Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")

列表显示的状态很好,但它不会自动选择我分配的值(“墨尔本”)。我曾尝试使用 selectlist 构造函数来分配 selectedValue,但经过大量研究后,有人写道,如果您使用 Html.DropdownListFor(),则使用 selectlist 构造函数是多余的,因为您将使用分配给模型的值。

编辑:

这是我的 db.State 模型:

public class State
{
    [Key]
    public int StateId { get; set; }
    public string StateName { get; set; }

}

再次澄清,我想使用 StateName 作为选择列表项的值和文本。

编辑: 我的完整动作方法:

public ActionResult EditInformation()
    {
        //var states = ndb.States.Select(s => new SelectListItem { Text = s.StateName, Value = s.StateName , Selected = s.StateName == "Jawa Timur" }).ToList();

        ViewBag.State = new SelectList(ndb.States, "StateName", "StateName");
        ViewBag.City = new SelectList(ndb.Cities, "CityName", "CityName");
        string[] countries = { "Indonesia" };
        ViewBag.Country = new SelectList(countries);

        string userEmail = User.Identity.GetUserName();
        try
        {
            UserInformation userInfo = ndb.UserInformations.Single(m => m.Email == userEmail);
            UserAccountViewModel model = new UserAccountViewModel();

            model.Address = userInfo.Address;
            model.Email = userEmail;
            model.FirstName = userInfo.FirstName;
            model.LastName = userInfo.LastName;
            model.Phone = userInfo.Phone;
            model.PostalCode = userInfo.PostalCode;
            Debug.Print(userInfo.State);
            model.State = userInfo.State;
            model.City = userInfo.City;
            model.Country = userInfo.Country;


            return View(model);
        }catch { }
        return View();

    }

【问题讨论】:

  • 你的db.States是什么样的?
  • 你为什么要发布SampleModel 的模型,然后在你的ViewBag 中塞满db.States 的东西?为States 发布您的模型。你的db.StatesID 吗?
  • @BviLLe_Kid,实际上模型还有更多内容,我只是简化它以便你们更好地阅读,其余的只是简单的属性,它们按预期工作。我的 db.States 有一个 ID,但我更喜欢使用名称作为值。

标签: c# asp.net-mvc


【解决方案1】:
public ActionResult EditInformation(int? id /*this will be passed from your route values in your view*/)
{
    State myState = db.States.Find(id)


    ViewBag.State = new SelectList(ndb.States, "StateId", "StateName", myState.StateId);
}//I only added this because this is what the question pertains to.

在您的 EditInformation 视图中,您需要有一个操作链接来链接到用户的 id,以便您提取正确的信息,所以:

编辑信息视图:

@foreach (var item in Model)
{
    @Html.ActionLink("Edit Information", "EditInformation", /*Controller Name if this view is rendered from a different controller*/, new { id = item.id })
}

【讨论】:

  • 如果我想要名称作为值怎么办?不是身份证
  • @StewartJingga 所以你已经尝试过这个解决方案,它呈现ID而不是State
  • @BviLLe_Kid 我尝试使用 StateId 仍然无法正常工作。
  • @StewartJingga 发生了什么?它根本不工作或显示ID
  • @BviLLe_Kid 完美显示列表,但不会自动选择所选值。
【解决方案2】:

试试这个:

public class SampleModel
{        
    public int Id { get; set; }
    public string State { get; set; }
}

控制器:

public ActionResult EditInformation()
{
    //Select default value like this (of course if your db.States have an Id):
    ViewBag.State = new SelectList(db.States, "Id", "StateName", 1 /*Default Value Id or Text*/);
    . . .
    return View();
}

SelectList(IEnumerable, String, String, Object) - 使用列表的指定项、数据值字段、数据文本字段、和选定值来初始化 SelectList 类的新实例。

查看:

@Html.DropdownList("State", null, "-- Select State --")

或者像你一样:

@Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")

更新:

您可以像这样使用 jQuery 获取 Selected 文本: 添加@Html.HiddenFor(x =&gt; x.State)

@Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --", new { id = "stateId" })
@Html.HiddenFor(x => x.State)

JS:

$(function () {
$("form").submit(function(){
    var selectedText= $("#stateId :selected").text();
    $("#State").val(selTypeText);           
  });
});

帖子:

[HttpPost]
public void UploadDocument(State model)
{
   if(ModelState.IsValid)
   {
      string state = model.State;
   }
}

【讨论】:

  • 感谢您的回答,但我希望selectlistitem的值与文本相同。
  • 感谢您的帮助,但我更关心导致它的原因而不是让它起作用。
  • ViewBag.State = new SelectList(db.States, "Id", "StateName", 1); 替换为ViewBag.State = new SelectList(db.States, "StateName", "StateName", "Melbourne"); 时会发生什么
  • 使用您推荐的解决方案,我不得不将 model.State 属性更改为整数,它仍然显示列表,但它没有选择所选值或模型中的值。跨度>
  • 您不需要将model.State更改为整数,您只需要使用Text和Value创建您的SelectList然后将其绑定到DropDowList,使用jQuery之后您可以得到选择来自DropDownList 的文本值,这是您的解决方案。
【解决方案3】:

好的,所以经过一段时间的研究,问题在于命名约定。显然,您不能将ViewBag.State 用于Html.DropdownListFor(m =&gt; m.State),这会导致Html.DropdownListFor(m =&gt; m.State) 无法正确读取数据。

【讨论】:

  • 所以你把它改成了@Html.DropDownList("State", null, --Select State--)
  • 不,我将ViewBag,State 更改为ViewBag.States,只要它不是State(没有s,因为它是模型的属性)它就可以工作。如果您使用的是DropdownList,则应该使用ViewBag.State,因为您无法为表单分配名称和ID。
猜你喜欢
  • 2012-10-10
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多