2011-07-08 33 views
2

我對JQuery和MVC很新。在我的應用程序中,我打開了一個按鈕單擊的JQuery模式對話框。如何顯示服務器端驗證錯誤後的Jquery模式對話框

public ActionResult Create() 
{      
    return PartialView("Create"); 
} 

局部視圖包含一些文本框和「創建」按鈕:我使用的控制器的操作方法是這樣的對話框上呈現局部視圖。在創建按鈕我試圖將數據保存在數據庫中。但在此之前,我做了一些驗證,如輸入的名稱已存在,然後將該消息顯示給用戶。 我這樣做是使用下面的代碼:

return PartialView("Create", model); 

這正顯示出正確的消息,但它在瀏覽器中只呈現局部視圖和模態對話框被消失。

請讓我知道如何顯示與錯誤相同的模態對話框。

回答

10

您將需要使用AJAX提交表單。以下是如何繼續。

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult Create() 
    { 
     return PartialView("Create"); 
    } 

    [HttpPost] 
    public ActionResult Create(MyViewModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      return PartialView(model); 
     } 
     // TODO: the model is valid => do some processing with it 
     // and return a JSON result confirming the success 
     return Json(new { success = true }); 
    } 
} 

和主視圖(~/Views/Home/Index.cshtml):

public class MyViewModel 
{ 
    public string Foo { get; set; } 

    [Required(ErrorMessage = "The bar is absolutely required")] 
    public string Bar { get; set; } 
} 

然後控制器:

<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script> 
<script type="text/javascript"> 
    // Remark: all this javascript could be placed in a separate js file 
    // to avoid cluttering the views 
    $(function() { 
     $('#modalLink').click(function() { 
      $('#dialog').load(this.href, function() { 
       $(this).dialog(); 
       bindForm(this); 
      }); 
      return false; 
     }); 
    }); 

    function bindForm(dialog) { 
     $('form', dialog).submit(function() { 
      $.ajax({ 
       url: this.action, 
       type: this.method, 
       data: $(this).serialize(), 
       success: function (result) { 
        if (result.success) { 
         alert('thanks for submitting'); 
         $('#dialog').dialog('close'); 
        } else { 
         $('#dialog').html(result); 
         bindForm(); 
        } 
       } 
      }); 
      return false; 
     }); 
    } 
</script> 


@Html.ActionLink("open modal", "create", null, null, new { id = "modalLink" }) 
<div id="dialog"></div> 

一如既往以期模型,其將代表對話形式中的信息開始和部分視圖(~/Views/Home/Create.cshtml),其中將包含模式中顯示的形式:

@model MyViewModel 
@using (Html.BeginForm()) 
{ 
    <div> 
     @Html.LabelFor(x => x.Foo) 
     @Html.EditorFor(x => x.Foo) 
     @Html.ValidationMessageFor(x => x.Foo) 
    </div> 
    <div> 
     @Html.LabelFor(x => x.Bar) 
     @Html.EditorFor(x => x.Bar) 
     @Html.ValidationMessageFor(x => x.Bar) 
    </div> 
    <input type="submit" value="OK" /> 
} 
相關問題