【发布时间】:2013-10-04 03:16:55
【问题描述】:
您好,我的问题是:我有两个 div,一个 div 包含 @ajax.beginform,另一个 div 为空但隐藏。我的想法是,带有表单的div,发出ajax请求,控制器的action方法检测模型是否有效,如果无效,重新发送相同的内容表单(包含表单内容的一个局部视图)但存在验证错误; 如果模型有效,它会返回另一个带有简单“谢谢”的partialview内容并显示在div中是隐藏的,那么它应该隐藏具有表单的div。我不知道我该怎么做???我的想法是@ajax.beginform的onSuccess事件作为参数,服务器返回的html,但不知道返回服务器的内容是什么,即不知道显示什么div。请帮帮我。
PD:如果问题不明白,请告诉我,我会举个例子。
[[[[[[更新]]]]]]
我有一个模型:
public class Message{
public int MessageID { get; set; }
[Required]
public string From { get; set; }
[Required]
public string Content { get; set; }
}
我有一个控制器:
public class MessageController : Controller{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult saveMessage(Message msg) {
// (ModelState.IsValid)
if (!msg.From.Contains("@")) {
ModelState.AddModelError("From", "The mail must contain an @");
return PartialView("DataMsg", msg);
}
return RedirectToAction("thanks");
}
public PartialViewResult thanks() {
return PartialView();
}
}
和我的观点:
Index.cshtml:
@model MvcApplication1.Models.Message
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@section scripts{
<script>
function successMsg(data) {
// I want the "thank you" is displayed in the div with id="thanksUpdate" and not in #formUpdate
$("#formUpdate").html(data);
}
</script>
}
@using (Ajax.BeginForm("saveMessage",
new AjaxOptions { HttpMethod="Post", OnSuccess="successMsg"})) {
<div id="formUpdate">
@Html.Partial("DataMsg", Model);
</div>
}
<div id="thanksUpdate" style="display:none;">
</div>
DataMsg.cshtml:
@model MvcApplication1.Models.Message
@Html.LabelFor(m => m.From)
@Html.EditorFor(m => m.From)
@Html.ValidationMessageFor(m => m.From)
@Html.LabelFor(m => m.Content)
@Html.EditorFor(m => m.Content)
@Html.ValidationMessageFor(m => m.Content)
<input type="submit" value="Send" />
和thanks.cshtml:
<h2>Thank you</h2>
我希望“谢谢”显示在 id="thanksUpdate" 的 div 中,而不是在 #formUpdate 中。我怎么能这样???
【问题讨论】:
-
向服务器发送数据和处理它接收到的数据的服务器是两个完全不同的主题。如果你有任何代码,你应该发布它。
-
嗨乔恩,我会添加必要的代码
标签: jquery ajax asp.net-mvc