如果我理解正确,您的页面上有一个创建事件表单,并且您想发送一个 AJAX 请求来创建一个新事件。然后,您想#content
用操作的结果替换页面中的一个部分CreateEvent
。
看起来您的 AJAX 设置正确,以便CreateEvent
返回成功的响应。我想你现在对回应感到困惑。你有几个选择,但让我们选择两个。
JSON 响应
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return Json(event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
...
现在您需要从 JSON 生成 html 标记并将其插入到#content
.
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
var obj = JSON.Parse(data);
var html; // build html with the obj containing server result
$("#content").html(html);
}
})
或HTML 片段
而不是返回一个完整的页面,Layout
我们将只返回一个PartialView
没有Layout
和所有的head
和script
标签。
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return PartialView("CreateEventResult", event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
}
现在创建一个新的局部视图CreateEventResult.cshtml (Razor)
@model Namespace.EventModelResult
@ {
Layout = null;
}
<div>
<!-- this stuff inserted into #content -->
@Model.Date
...
</div>
and the javascript is unchanged
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
Edit:
If your Event creation fails for any reason after you have validated the input, you'll have to decide how you want to respond. One option is to add a response status to the object you return and just display that instead of the newly created Event.