您好我有一个注释模型,我想使用局部视图向数据库添加一些注释...我想要的是刷新局部视图而不刷新所有视图.. 我现在得到的是,当我向数据库插入数据时,日期存储在数据库中,但我必须刷新页面才能看到它...局部视图不会立即刷新。
这是我的代码:
//model
public partial class Commentaire
{
public int CommentaireId { get; set; }
public string TxtCommentaire { get; set; }
public System.DateTime DateCommentaire { get; set; }
}
视图模型:
public class CommentaireViewModel
{
public Commentaire NVcommentaire { get; set; }
public IEnumerable<Commentaire> Commentaires { get; set; }
}
索引视图:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
@using (Ajax.BeginForm("Index_AddItem", new AjaxOptions { UpdateTargetId = "productList" }))
{
<fieldset>
<legend>Commentaire</legend>
<div class="editor-label">
@Html.LabelFor(model => model.NVcommentaire.TxtCommentaire)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.NVcommentaire.TxtCommentaire)
@Html.ValidationMessageFor(model => model.NVcommentaire.TxtCommentaire)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.NVcommentaire.DateCommentaire)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.NVcommentaire.DateCommentaire)
@Html.ValidationMessageFor(model => model.NVcommentaire.DateCommentaire)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<div id='productList'>
@{ Html.RenderPartial("ProductListControl", Model); }
</div>
}
部分观点:
<table class="table table-striped table-hover display" cellspacing="0" id="OrderTable">
<thead>
<tr>
<th>txt</th>
<th>date</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Commentaires)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.TxtCommentaire)</td>
<td>@Html.DisplayFor(modelItem => item.DateCommentaire)</td>
<td>
@Html.ActionLink("Modifier", "Edit", new { id = item.CommentaireId }) |
</td>
</tr>
}
</tbody>
</table>
最后是控制器:
public ActionResult Index()
{
CommentaireViewModel viewModel = new CommentaireViewModel
{
NVcommentaire = new Commentaire(),
Commentaires = db.Commentaires
};
return View(viewModel);
}
public ActionResult Index_AddItem(CommentaireViewModel viewModel)
{
db.Commentaires.Add(viewModel.NVcommentaire);
db.SaveChanges();
return PartialView("ProductListControl", db.Commentaires);
}
答案 0 :(得分:3)
我认为您的ajax请求失败是因为部分视图的预期Model
类型导致的异常并且收到了一个不匹配。
在部分视图中,您有:@foreach (var item in Model.Commentaires)
表示您的Model
具有Commentaires
属性。
在您的控制器操作的返回语句中,您有return PartialView("ProductListControl", db.Commentaires);
,这意味着您将IEnumerable<Commentaire>
作为Model
传递给您。这与您在部分视图中具有的Model
类型相矛盾。
可能的解决方案:
Model
类型更改为IEnumerable<Commentaire>
foreach
更改为@foreach (var item in Model)
@{ Html.RenderPartial("ProductListControl", Model); }
代码更改为@{ Html.RenderPartial("ProductListControl", Model.Commentaires); }