我在访问控制器
中的viewmodel及其部分视图模型数据时遇到问题我的模特
public class SearchRequest : BaseRequest
{
public SearchOptions SearchBy{ get; set; }
// and other properties also there
}
[KnownType(typeof(SearchByAirport))]
[KnownType(typeof(SearchByCity))]
[KnownType(typeof(SearchByProductCodes))]
[KnownType(typeof(SearchByGeocode))]
public abstract class SearchOptions
{
}
public class SearchByProductCodes : SearchOptions
{
public List<string> Codes { get; set; }
}
public class SearchByGeocode : SearchOptions
{
// few more properties
}
我的观点
View有SearchRequest
的模型参考,并且有一个用于选择搜索类别的下拉列表(即按产品代码,地理位置代码,城市等搜索等),并且在下拉列表更改时加载我的局部视图< / p>
我的部分观点之一
@model Tavisca.Catapult.External.DataContract.Common.SearchByProductCodes
<div class="form-group">
@Html.LabelFor(model => model.Codes, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Codes)
</div>
</div>
控制器
[HttpPost]
public ActionResult Create(SearchRequest hotelSearchRequest)
{
return View();
}
我在这里得到SearchBy
Null,安排我的视图并从视图到控制器获取所有字段的最佳方法是什么。
答案 0 :(得分:0)
模型绑定器会尝试将表单值中的代码与您的viewmodel匹配,但在那里称为SearchBy,因此它将失败。
尝试这样做
<div class="form-group">
@Html.LabelFor(model => model.Codes, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Codes, new {Name="SearchBy" })
</div>
</div>
这将为模型绑定器提供正确的字段名称。
另一种方法是从控制器操作中的表单手动获取它,如下所示:
Request.Form["Codes"]
就个人而言,我会选择#1选项。