[英]asp.net mvc insert data in database and refresh partial
嗨,我有一個注釋模型,我想使用局部視圖添加一些注釋到數據庫...我想要的是刷新局部視圖而不刷新所有視圖..我現在得到的是當我向數據庫插入數據時日期存儲在數據庫中,但我必須刷新頁面才能看到它...局部視圖不會立即刷新。
這是我的代碼:
//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);
}
我認為您的ajax請求失敗是因為部分視圖的預期Model
類型導致的異常並且收到了一個不匹配。
在您的部分視圖中,您有: @foreach (var item in Model.Commentaires)
,這意味着您的Model
具有Commentaires
屬性。
在你的控制器動作的return語句中你有: 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); }
代碼中以@{ Html.RenderPartial("ProductListControl", Model.Commentaires); }
@{ Html.RenderPartial("ProductListControl", Model.Commentaires); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.