我在编辑视图中有以下内容: -
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Rack.RackID)
@Html.HiddenFor(model => model.Resource.RESOURCEID)
@Html.HiddenFor(model => model.Rack.timestamp)
@Html.HiddenFor(model=>model.Rack.Technology)
<span class="f"> @Html.TextBoxFor(model => model.Rack.Technology.Tag, new
{ @readonly = "readonly" })</span>
<span class="f">Rack Name </span>
@Html.EditorFor(model => model.Resource.RESOURCENAME)
@Html.ValidationMessageFor(model => model.Resource.RESOURCENAME)
</div>
<div >
<span class="f">Product Name </span>
@Html.DropDownList("productName", ((IEnumerable<TMS.Models.ComponentDefinition>)ViewBag.Products).Select(option => new SelectListItem {
Text = (option == null ? "None" : option.COMPONENTNAME),
Value = option.COMPONENTNAME.ToString(),
Selected = (Model != null) && (Model.Resource.ComponentDefinition != null ) && (option.COMPONENTNAME == Model.Resource.ComponentDefinition.COMPONENTNAME)
}), "Choose...")
@Html.ValidationMessageFor(model => model.Resource.COMPONENTID)
</div>
<input type="submit" value="Save" class="btn btn-primary"/>
}</div>
我有以下Post Edit操作方法: -
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RackJoin rj,FormCollection formValues)
{
string controllername = RouteData.Values["controller"].ToString();
try
{
if (ModelState.IsValid)
{
var message = "";
var status = "";
long assetid = new long();
XmlDocument doc = new XmlDocument();
using (var client = new WebClient())
{ var query = HttpUtility.ParseQueryString(string.Empty);
foreach (string key in formValues)
{
query[key] = this.Request.Form[key];
}
和RackJoin模型类是: -
public class RackJoin
{
public Rack Rack { get; set; }
public Resource Resource { get; set; }}
但我遇到的问题是,当我将对象回发到Post Edit操作方法时,我将丢失其所有导航属性,例如(Rack.Technology,Rack.SiteDefinistion),所以我如何能够维护所有对象导航属性,因此如果Post编辑操作方法想要访问这些导航属性,或者在模型状态错误之后呈现编辑视图,则它们将不会获得空引用异常。
答案 0 :(得分:2)
这不起作用的原因是因为Technology
是复杂类型,因此无法通过HiddenFor
呈现,如果您需要保留此属性的所有信息,则必须单独渲染每个属性,例如
@Html.HiddenFor(model => model.Rack.Technology.Name)
但是,我开始质疑你的设计了。如果很多信息与这个特定的观点无关,那么事实上它甚至不应该存在。视图模型应根据视图进行定制,因此我建议您使用特定的模型,以便仅捕获相关信息,即
public class RackJoinViewModel
{
public int RackID { get; set; }
public int ResourceID { get; set; }
public DateTime TimeStamp { get; set; }
public string Technology { get; set; }
...
}
这应该简化视图渲染,因为没有复杂的类型,例如。
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.RackID)
@Html.HiddenFor(model => model.ResourceID)
@Html.HiddenFor(model => model.TimeStamp)
@Html.HiddenFor(model => model.Technology)
...
}
这不仅更清洁,而且还消除了尝试在请求中保留不相关信息的问题。