我有一个非常简单的"InddexView“,它显示了已经在数据库中的条目的细节。在相同的视图中,我有一个create条目链接。使用Ajax.Actionlink单击create链接以更新同一个"IndexView“上的div,并显示带有文本框和按钮的create视图.现在,在“创建”View.cshtml上,我使用$.ajax通过ajax创建新条目。正在数据库中创建条目,但没有刷新主"IndexView“以显示新创建的条目。请帮助我如何做那件事?
这是我的_Create.Cshtml代码,用于显示所有条目。
@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“
寻求帮助..。
这是我的控制器动作"CreateViaAjax“
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());
}下面是我在CreateEntry链接上点击时调用的CreateEntry
public ActionResult Create()
{
return PartialView("_Create");
}=================================
发布于 2011-09-06 05:38:01
以下是几种可能性:
success回调中,向控制器操作发送另一个AJAX请求,该操作将读取条目并返回其刷新状态。当这个AJAX调用成功后,用新的内容替换容器:$('#entriesContainer').html(result);$('#entries').append('<li>new entry info</li>');window.location.href = '@Url.Action("Index", "Home")';。
https://stackoverflow.com/questions/7310603
复制相似问题