我在将 ViewModel 回发到控制器时遇到问题,但是 ViewModel 没有正确地从视图映射到控制器。
TopicId和Content应该包含值,但是,在回发时,它们不会:
VS调试:
视图模型:
public class PostViewModel
{
public int PostId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Author { get; set; }
public DateTime DateOfTopic { get; set; }
}
public class ReplyViewModel
{
public int TopicId { get; set; }
public string Content { get; set; }
}
public class PostListAndReplyVM
{
public List<PostViewModel> PostViewModel { get; set; }
public ReplyViewModel ReplyViewModel { get; set; }
}
看法:
@model centreforum.Models.PostListAndReplyVM
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Post</legend>
@Html.HiddenFor(model => model.ReplyViewModel.TopicId)
<div class="editor-label">
@Html.LabelFor(model => model.ReplyViewModel.Content)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ReplyViewModel.Content)
@Html.ValidationMessageFor(model => model.ReplyViewModel.Content)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
生成的 HTML:
<form action="/Post/List/7/" method="post"><input name="__RequestVerificationToken" type="hidden" value="xxxxxxxxxxxxx" /> <fieldset>
<legend>Post</legend>
<input data-val="true" data-val-number="The field TopicId must be a number." data-val-required="The TopicId field is required." id="ReplyViewModel_TopicId" name="ReplyViewModel.TopicId" type="hidden" value="7" />
<div class="editor-label">
<label for="ReplyViewModel_Content">Content</label>
</div>
<div class="editor-field">
<input class="text-box single-line" id="ReplyViewModel_Content" name="ReplyViewModel.Content" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="ReplyViewModel.Content" data-valmsg-replace="true"></span>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
从生成的 HTML 中可以看出,TopicId 肯定有一个值:value="7"
任何人都可以看到表单帖子和控制器之间的问题所在,而控制器需要ReplyViewModel?
谢谢,
标记