如何使用我计划在多个地方使用的表单帖子创建部分视图?
部分视图将有一个表单,用于在数据存储中创建条目并在此表单下显示持久数据。 因此,在提交表单后,我将在表单下的网格状结构中看到我的条目而不切换父视图。 如果模型无效,则也会显示错误。这里的诀窍是,如何在不创建动作的情况下保留当前页面 在每个视图的控制器中显示局部视图?
我会在10个不同的父视图中使用这个局部视图。
下面,我提供一些有助于社区准确理解问题的代码。
我应该如何配置我的代码以实现我的目标。
由于
这是局部视图样本
@model ViewModels.CommentViewModel
@using (Html.BeginForm("Index", "Comment", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary()
<div class="form-group">
<label class="control-label col-md-2">Please Type Your Name</label>
<div class="col-md-10">
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<input id="addComment" type="submit" value="Add" />
</div>
}
@foreach (var item in Model.Comments)
{
<p>
@item.Name
</p>
}
这是控制器
public PartialViewResult Index(int id)
{
var model = new CommentViewModel() { Comments= db.Comments.Where(x=> x.NewsId == id && x.isApproved== true )};
return PartialView("_Comments", model);
}
[HttpPost]
public PartialViewResult Comment(int id, CommentViewModel model)
{
if (ModelState.IsValid)
{
var comment = new Comment()
{
Name = model.Name,
Title = model.Title,
CommentContent = model.Content,
Email = model.Email,
CreationDate = DateTime.Now,
RefId = Guid.NewGuid(),
isApproved = false,
NewsId = id
};
db.Comments.Add(comment);
db.SaveChanges();
return PartialView();
}
return PartialView();
}
答案 0 :(得分:0)
如果你想做一些事情,比如提交表格并检索更新的数据而不重新加载页面,那么你就是在谈论AJAX。在这种情况下,这是局部视图的事实毫无意义。这个局部视图将呈现多少个不同的视图无关紧要,您只需要一个控制器中的一个动作就可以响应AJAX请求。然后,您只需要使用JavaScript执行以下操作,可以通过外部文件包含在需要此表单的任何视图中:
$('#MyPartialViewForm').on('submit', function (e) {
// prevents form from submitting standard way, causing page refresh
e.preventDefault();
$.post('/url/that/handles/form', $(this).serialize(), function (results) {
// results will be a rendered partial with the data here,
// which you can use to replace the content of a div or
// something on your page.
$('#DivWhereSubmittedDataIsDisplayed').html(results);
});
});
然后,在响应AJAX请求的操作中:
[HttpPost]
public ActionResult ActionForAjaxForm(FormModel model)
{
// do something like save the posted model
return PartialView("_PartialViewThatRendersData", model);
}