我有一个非常简单的“InddexView”,它显示了数据库中已有的条目的详细信息。在同一个视图上我有一个创建条目链接。使用Ajax.Actionlink单击创建链接以更新相同“IndexView”上的div并显示带有文本框和按钮的创建视图...现在在“创建”View.cshtml上我使用$ .ajax创建新的通过ajax输入。条目正在数据库中创建,但没有刷新主“IndexView”以显示新创建的条目..请帮助解决该怎么做?。
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset id="fsShowCreatestatus">
<legend>Entries</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Body)
@Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Create" id="btnCreate" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
$('#btnCreate').click(function (e) {
var title = $('#Title').val();
var body = $('#Body').val();
var postdata = {
"Title": title,
"Body": body
};
e.preventDefault();
callajax(postdata);
});
function callajax(data) {
$.ajax({
url: '@Url.Action("CreateViaAjax","Home")',
data: data,
success: function (returnData) {
$('#divCreateNew').slideUp(100).fadeOut(50);
alert('Ajax-completed');
$('#divShowDetails').appendTo('#divEdit');
},
error: function (returndata) {
$('#divCreateNew').appendTo('#fsShowCreateStatus').html('there was an error while adding the entry');
}
});
}
</script>
here is my index view which the main view and using for showing partial view(_Create) and the link for creating the new one..
=======================================
<h2>Index</h2>
<div id="divCreateLink">
<p>
@Ajax.ActionLink("Create New", "Create","Home", new AjaxOptions {
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
UpdateTargetId = "divCreateNew",
})
</p>
</div>
<div id="divCreateNew">
</div>
<div id="divEdit">
</div>
@Html.Partial("PartialCreate")
代码被执行但没有刷新“IndexView”
寻求帮助......public ActionResult CreateViaAjax(Entries entries)
{
if (ModelState.IsValid)
{
db.DBEntries.Add(entries);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(entries);
}
public ViewResult Index()
{
return View(db.DBEntries.ToList());
}
public ActionResult Create()
{
return PartialView("_Create");
}
=================================
答案 0 :(得分:1)
以下是几种可能性:
success
回调中,向控制器操作发送另一个AJAX请求,该操作将读取条目并返回其刷新状态。当此AJAX调用成功时,使用新内容替换容器:$('#entriesContainer').html(result);
$('#entries').append('<li>new entry info</li>');
附加此新条目window.location.href = '@Url.Action("Index", "Home")';