您好我有一个评论模型,我想使用部分 View 向数据库添加一些评论...我想要的是刷新部分 View 而不刷新所有 View .. 我现在得到的是,当我将数据插入数据库时,日期存储在数据库中,但我必须刷新页面才能看到它。部分 View 不会立即刷新。
这是我的代码:
//model
public partial class Commentaire
{
public int CommentaireId { get; set; }
public string TxtCommentaire { get; set; }
public System.DateTime DateCommentaire { get; set; }
}
View 模型:
public class CommentaireViewModel
{
public Commentaire NVcommentaire { get; set; }
public IEnumerable<Commentaire> Commentaires { get; set; }
}
索引 View :
<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>
}
局部 View :
<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>
最后是 Controller :
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);
}
最佳答案
我认为您的 ajax 请求失败是因为预期的 Model
引起的异常键入部分 View 并收到一个不匹配项。
在您的部分 View 中,您有:@foreach (var item in Model.Commentaires)
这意味着你的 Model
有一个 Commentaires
属性(property)。
在 Controller 操作的返回语句中,您有:return PartialView("ProductListControl", db.Commentaires);
这意味着您正在通过 IEnumerable<Commentaire>
作为Model
给你看。这与 Model
的类型相矛盾你有部分 View 。
可能的解决方案:
- 更改您的
Model
键入IEnumerable<Commentaire>
的部分 View - 更改
foreach
部分 View@foreach (var item in Model)
- 更改
@{ Html.RenderPartial("ProductListControl", Model); }
代码查看@{ Html.RenderPartial("ProductListControl", Model.Commentaires); }
关于c# - asp.net mvc 在数据库中插入数据并刷新部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36088598/