[英]Unable to get new selected value of @Html.DropDownListFor in case of using autobinding
Unable to bind model with value from @Html.DropDownListFor field in MVC3 (razor) of a strongly typed view. 无法使用强类型视图的MVC3(razor)中的@ Html.DropDownListFor字段中的值绑定模型。
Model used for strongly typed view: 用于强类型视图的模型:
public class MyModel
{
public string Name{get;set;}
pulic int Status_ID{get;set;}
}
In strongly typed view: 在强类型视图中:
@Html.DropDownListFor(m=> m.Status_ID, new SelectList(Repo.AllStatus, "ID", Name"), new {@style = "width: 100%;" })
Before submitting the form I selected the option with ID=24(ie value=24 option is selected) 在提交表单之前,我选择了ID = 24的选项(即选择了值= 24选项)
In controller 在控制器中
public ActionResult AddMyModel(MyModel myModel)
{
}
While debugging, in controller, I got that: myModel.Name is expected value but myModel.Status_ID is 0 not 24 在调试时,在控制器中,我得到了:myModel.Name是期望值,但myModel.Status_ID是0而不是24
where am I going wrong?? 我哪里错了?
You need to pass in a view model to your view with all the statuses already populated. 您需要将视图模型传递到视图,并且已填充所有状态。
Here is a solution to your problem. 这是您的问题的解决方案。 Modify it to fit in with your scenario. 修改它以适应您的方案。 I hope I haven't left out anything. 我希望我没有遗漏任何东西。 The code below is what I am assuming your models might look like. 下面的代码是我假设您的模型可能看起来像。
Your status class: 你的状态类:
public class Status
{
public int Id { get; set; }
public string Name { get; set; }
}
On your view you need to pass in a view model that contains a list of all your statuses: 在您的视图中,您需要传入包含所有状态列表的视图模型:
public class YourViewModel
{
public int StatusId { get; set; }
public IEnumerable<Status> Statuses { get; set; }
}
Your controller: 你的控制器:
public class YourController : Controller
{
private readonly IStatusRepository statusRepository;
public YourController(IStatusRepository statusRepository)
{
this.statusRepository = statusRepository;
}
public ActionResult YourAction()
{
YourViewModel viewModel = new YourViewModel
{
Statuses = statusRepository.FindAll()
};
return View(viewModel);
}
}
And then your view will look something like this: 然后您的视图将如下所示:
@model YourProject.ViewModels.Statuses.YourViewModel
@Html.DropDownListFor(
x => x.StatusId,
new SelectList(Model.Statuses, "Id", "Name", Model.StatusId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.StatusId)
I hope this can help you in the right direction and shed some light on what you are trying to achieve. 我希望这可以帮助你朝着正确的方向前进,并阐明你想要实现的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.