【发布时间】:2015-07-23 05:10:04
【问题描述】:
我正在使用 ViewModel 来检索控制器操作中输入的数据。但是 ViewModel 在它的属性中得到了空值。我正在创建一个局部视图
在该局部视图中,我通过绑定 ViewModel 创建 下拉列表,然后在其他 View中渲染该局部视图>
下面是我的代码
我的视图模型:
public class LookUpViewModel
{
RosterManagementEntities rosterManagementContext = new RosterManagementEntities();
public LookUpViewModel()
{
tblCurrentLocations = from o in rosterManagementContext.tblCurrentLocations select o;
tblStreams = from o in rosterManagementContext.tblStreams select o;
}
[Required]
public virtual IEnumerable<tblCurrentLocation> tblCurrentLocations { get; set; }
[Required]
public virtual IEnumerable<tblStream> tblStreams { get; set; }
我的部分观点:
@model PITCRoster.ViewModel.LookUpViewModel
@Html.Label("Location")
@Html.DropDownListFor(M=>M.tblCurrentLocations, new SelectList(Model.tblCurrentLocations, "LocationId", "Location"), "Select Location")
@Html.ValidationMessageFor(M=>M.tblCurrentLocations)
<br />
@Html.Label("Stream")
@Html.DropDownListFor(M => M.tblStreams, new SelectList(Model.tblStreams, "StreamId", "Stream"), "Select Streams")
@Html.ValidationMessageFor(M => M.tblStreams)
我在其中渲染此部分视图的视图
@{
ViewBag.Title = "Resources";
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<h2>Resources</h2>
@using (Html.BeginForm("AddResource", "Resources", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
Html.RenderPartial("_LookUpDropDowns", new PITCRoster.ViewModel.LookUpViewModel());
<br />
<input type="submit" value="Create" />
}
这是我的控制器操作方法: [HttpPost]
public void AddResource(LookUpViewModel testName)
{
//code
}
当我在我的控制器操作方法上放置一个调试器时,控制转到该操作方法。 但是 ViewModel 对象中有 null 。 我尝试使用 FormCollection 对象访问输入的值,并且按预期获取所有数据...
以下是我使用 FormCollection 进行控制器操作的代码
[HttpPost]
public void AddResource(FormCollection form)
{
var x = form["tblStreams"]; //I get value here..
}
谁能解释一下为什么我没有在 ViewModel 对象中获取值? 谢谢...
【问题讨论】:
-
您不能将下拉列表绑定到复杂对象的集合(
<select>仅回发单个值(所选选项的值)。您的视图模型需要绑定属性 - 例如 @ 987654327@ 和所选流的同上 -
您期望发生什么,您正在寻找什么值,此视图模型的编码方式将在每次使用时转到您的数据存储区,只需选择
tblCurrentLocations和 'tblStreams' .此外,您的下拉菜单将所选值分配给您在视图模型构造函数中填充的相同列表 -
@StephenMuecke 你能用一些代码解释一下吗?
标签: c# asp.net-mvc asp.net-mvc-4