[英]Html.DropDownListFor doesn't select the right object
View 视图
@Html.DropDownListFor(model => model.ObjectId,
Model.SelectListItems,
"Default",
new { @id = "DropDown" })
Controller 调节器
TheViewModel model = ((TheViewModel )Session[nameof(TheViewModel )]);
if (model == null)
{
// fill model with data
}
return View(model);
I load the viewmodel from the session and want now to set the selected value by the id (from the model), but it doesn't work on this way. 我从会话中加载了viewmodel,现在想通过id(从模型中)设置选定的值,但是这种方式不起作用。 But in the post method I get the right information in my model and when i load the data from the session is also everything set. 但是,在post方法中,我可以在模型中获取正确的信息,并且从会话加载数据时,也可以设置所有内容。
Please notice that I don't want to use viewbag 请注意,我不想使用Viewbag
Both vars are set in the controller. 两个变量都在控制器中设置。 ObjectId is an int ObjectId是一个int
Thank you in advance. 先感谢您。
Please try this: 请尝试以下方法:
Model: 模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Testy20161006.Models
{
public class AnItem
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TheViewModel
{
public TheViewModel()
{
items.Add(new AnItem { Id = 1, Name = "dh1" });
items.Add(new AnItem { Id = 2, Name = "dh2" });
items.Add(new AnItem { Id = 3, Name = "dh3" });
}
public string SelectedValue { get; set; }
public List<AnItem> items = new List<AnItem>();
public IEnumerable<SelectListItem> Items
{
get { return new SelectList(items, "Id", "Name"); }
}
public string RequiredValidationMessage { get; set; }
}
}
Controller: 控制器:
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index26(TheViewModel m)
{
var selectedText = m.SelectedValue;
return View(m);
}
public ActionResult Index26()
{
TheViewModel m = new TheViewModel();
return View(m);
}
View: 视图:
@model Testy20161006.Models.TheViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index26</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.SelectedValue)
@Html.DropDownListFor(m => m.SelectedValue,
new SelectList(Model.Items, "Value", "Text"))
<input type="submit" value="Get Value of dropdown" />
}
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.