回发时,我的viewmodel中的模型始终为NULL。
请参阅我的代码:
这是控制器:
public ActionResult Create(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Query query = db.Queries.Find(id);
if (query == null)
{
return HttpNotFound();
}
var viewModel = new QueryViewModel(query);
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create (QueryViewModel viewModel, string Message)
{
//viewmodel processing here
//viewModel.Query is always null here
return View();
}
以下是观点:
@model ViewModels.QueryViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Query)
<div class="row">
<h2>Post a reply</h2>
</div>
<div class="row">
<div class="input-control textarea size12">
@Html.TextArea("Message")
</div>
</div>
<div class="row">
<input type="submit" value="Post Reply"/>
</div>
}
以下是2个模型和viewmodel:
public class Query
{
public long QueryID {get;set;}
/**
* some properties goes here...
**/
}
public class QueryReply
{
public long QueryReplyID {get;set;}
public long QueryID {get;set;}
/**
* some properties goes here...
**/
public virtual Query Query {get;set;}
}
public class QueryViewModel
{
public Query Query {get;set;}
public IEnumerable<QueryReply> QueryReplies {get;set;}
public QueryViewModel() {}
public QueryViewModel (Query query)
{
Query = query;
}
}
请帮忙,谢谢!
- 编辑 -
此外,如果我将ViewModel中的模型Query命名为&#39; Query&#39;,在回发时,viewModel.Query仍将为NULL。但是,如果我将ViewModel中的查询模型名称更改为&#39; QueryModel&#39; (或除Query之外的任何其他名称)viewModel.QueryModel将具有值。请问你能解释一下为什么会这样吗?再次感谢..
答案 0 :(得分:4)
您的HTML表单是什么样的?
我怀疑@Html.HiddenFor(m => m.Query.QueryID)
不打印任何内容。您需要打印特定的模型属性:
studentvector[1] = s1; //OK if there are at least two elements in studentvector
另见Is there some way to use @Html.HiddenFor for complete model?。