如何将模型错误加载到模态对话框中

时间:2013-01-15 14:11:18

标签: c# javascript asp.net-mvc modal-dialog modelstate

在使用javascript提交表单后,是否可以将模型状态错误加载到相同的模式对话框中?

我的代码是这样的:

控制器:

public ActionResult Create(MyModel model){
     if(ModelState.isValid){
           // DB Save
           return RedirectToAction("Index");
     }
     else{
           return View(model);
     }
}

Ajax方法

$.ajax({
       type: 'POST',
       url: '/Receipt/Create',
       cache: false,
       data: $("#CreateForm").serialize(),
       success: function (e) { window.location="/Controller/Action"; },
       error: function (e) { e.preventDefault(); /*Code here to load model error into page*/ }                
});

2 个答案:

答案 0 :(得分:1)

今天我已经用这样的问题解决了这个问题

public ActionResult Create(MyModel model){
 if(ModelState.isValid){
       // DB Save
       return RedirectToAction("Index");
 }
 else{
       return PartialView("_myPartialForm",model);
 }
}

$.ajax({
   type: 'POST',
   url: '/Receipt/Create',
   cache: false,
   data: $("#CreateForm").serialize(),
   success: function (e) { 
if(e.Valid){
    window.location="/Controller/Action";}
else{
    return false;
  } },
   error: function (e) { e.preventDefault();$("#mymodal").load(e) } 
 });

就像jmrnet所说的那样。感谢

答案 1 :(得分:0)

我能够通过Ajax.BeginForm方法和UpdateTargetId AjaxOption来实现这一目标。这是我使用的代码。它并不完全符合您的工作,但它应该指向正确的方向。

在视图中:

@using (Ajax.BeginForm(new AjaxOptions(){ UpdateTargetId="loginresult" }))
{
    <b>User:</b><br />
    @Html.TextBoxFor(m => m.UserName)<br />
    <br />
    <b>Password:</b><br />
    @Html.PasswordFor(m => m.Password)<br />
    <div id="loginresult"><br /></div>
    <input id="Button1" type="submit" value="Login" class="touch-button" />
}

在控制器中:

[HttpPost]
public ActionResult Index(LoginModel model)
{
    //Execute Log-in code.
    //Capture any errors and put them in the model.LoginResponse property.

    return PartialView("LoginResult", model);
}

LoginResult局部视图中:

@model MerchantMobile.Models.LoginModel

@if (String.IsNullOrEmpty(Model.LoginResponse))
{
    Html.RenderPartial("_AjaxRedirect", Url.Content("~/Home/Activity"));
}
else
{
    <div id="loginresult">
        <div style="color: Red; font-weight: bold;">
            @Model.LoginResponse
        </div>
    </div>
}

您可以轻松地将loginresult <div>替换为jquery ui使用的一个弹出模式对话框而不是仅显示div中的一些文本。

希望这有帮助!