[英]In ASP.NET MVC, how do I return a different view when submitting a form via ajax?
我正在嘗試在ASP.NET MVC中創建一個留言板。 我有兩個局部視圖,一個顯示一個消息(這是遞歸的,並且還將顯示所有子...消息),另一個顯示一個提交新消息的表單。 發布消息時,我希望表單通過ajax提交,並返回部分視圖以顯示消息(剛剛發布的消息)。
這是用於顯示表單(NewMessage)的局部視圖
@model Intranet.Entities.ForumRepository.Message
<div id="@Html.Raw("formbox" + Model.ParentID)">
@using (Ajax.BeginForm("NewMessage", new AjaxOptions { UpdateTargetId = "formbox" + Model.ParentID })) {
@Html.TextAreaFor(m => m.Text, new { @class = "responsebox" })
@Html.HiddenFor(m => m.ParentID)
<br /><input type="submit" value="Save Comment" class="savebutton" />
}
</div>
及其提交方法
[HttpPost]
public ActionResult NewMessage(ForumRepository.Message message) {
if (ModelState.IsValid) {
RouteData.Values.Add("Responses", message);
//message.SaveMessage();
return PartialView("DisplayMessage", message);
} else {
return PartialView(message);
}
}
當我嘗試提交表單時,表單視圖不會被DisplayMessage視圖替換。 它一直顯示表格。 在調試模式下運行表明后端代碼正在被調用。
我相當確定這與ajax代碼用來重新顯示的div在NewMessage視圖內部(它不能替換其自己的容器)有關,但是我不知道如何設置它這樣它才能起作用。
根據要求,這是一些渲染的HTML
<div id="formbox0">
<form action="/EventList/NewMessage/Q6UJ9A00T49L" data-ajax="true" data-ajax-mode="replace" data-ajax-update="#formbox0" id="form0" method="post"><textarea class="responsebox" cols="20" data-val="true" data-val-required="The Text field is required." id="Text" name="Text" rows="2">
</textarea><input data-val="true" data-val-number="The field ParentID must be a number." data-val-required="The ParentID field is required." id="ParentID" name="ParentID" type="hidden" value="0" /> <br /><input type="submit" value="Save Comment" class="savebutton" />
</form>
</div>
我更喜歡避免使用AjaxBeginForm方法,並且喜歡編寫手寫和Clean jQuery代碼。
我給容器div一個CSS類(commentItem),以便以后可以在我的jQuery選擇器中使用它。
@model Intranet.Entities.ForumRepository.Message
<h3> Enter your comment</h3>
<div id="formbox@Model.ParentID" class="commentItem">
@using(Html.BeginForm())
{
@Html.TextAreaFor(m => m.Text, new { @class = "responsebox" })
@Html.HiddenFor(m => m.ParentID)
<input type="submit" value="Save Comment" class="savebutton" />
}
</div>
<script type="text/javascript">
$(function(){
$(".savebutton").click(function(e){
var item=$(this);
e.preventDefault();
$.post("@Url.Action("NewMessage","EventList")",
item.closest("form").serialize(),function(data){
item.closest("div.commentItem").html(data);
});
});
});
</script>
此代碼將用從您的Action方法接收的內容替換現有的表單(或容器div中的任何內容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.