2012-09-29 18 views
1

我忘記了密碼頁面,用戶輸入用戶名並單擊「驗證」按鈕以檢查他所在的組。我們需要在頁面中顯示不同的部分視圖(現在我們假設它是電話號碼)。填寫有效的詳細信息後,成功後,我將重定向到一個新頁面,在那裏他將更新他的密碼,失敗時,我需要顯示錯誤消息。如何重定向到MVC3中的jQuery ajax調用的新頁面(以及模型)

現在我很難寫出突出顯示的代碼。

這裏是jQuery的AJAX功能的代碼觸發提交按鈕點擊

person = {UserName: $("#UserName").val(), Phone: $("#Phone").val() } 
$.ajax({ 
      type: 'POST', 
      url: '@Url.Action("ForgotPassword", "Customer")', 
      data: person, 
      dataType: 'json', 
      success: function (data) { 
       //This is the place I need help 
       if(data.IsDataValid){ 
        // redirect to new page passing the model object 
       } 
       else{ 
        //Show an error message without hiding the div 
       } 
      }, 
      failure: function() {     
      } 
     }); 

這裏是代碼控制器動作

[HttpPost] 
    [ValidateInput(true)] 
    public ActionResult ForgotPassword(RegisterModel model) 
    {    
     if (Request.IsAjaxRequest()) 
     { 
      Here is the logic which validates the user 
      return Json(new { regmodel = RegistrationModel }) 
     } 
    //If it is not ajax call I want to return the view 
     if (isUsergroup1 == true) 
     { 
      return View("View1", RegistrationModel); 
     } 
     else if (isUsergroup2 == true) 
     { 
      return View("View2", RegistrationModel); 
     } 
     else 
     { 
      return View(); 
     } 

    } 

請幫助。在此先感謝

+0

IsDataValid是RegistrationModel的屬性嗎? –

+0

@Tieson是的,但是當我提到你的答案時,我還需要將模型傳遞給控制器​​ – Bob

+0

在視圖中混合Javascript? **讓我毛骨悚然**。我建議你使用'data-'屬性來傳遞視圖中的特定URL並在腳本文件中讀取它們。 –

回答

1

這就是我們需要做的。我們無法傳遞模型,我們只能通過鏈接重定向傳遞參數。我們必須使用link.replace,因爲您可以直接將變量傳遞到Url.Action

person = {UserName: $("#UserName").val(), Phone: $("#Phone").val() } 
$.ajax({ 
     type: 'POST', 
     url: '@Url.Action("ForgotPassword", "Customer")', 
     data: person, 
     dataType: 'json', 
     success: function (data) { 
      //This is the place I need help 
      if(IsDataValid){ 
       var link = "@Url.Action("Actionname", "Controllername", new { username = "1", phone ="2" })"; 
        link = link.replace("1", data.username); 
        link = link.replace("2", data.phone); 
        alert(link); 
        window.location.href= link ; 
      } 
      else{ 
       //Show an error message without hiding the div 
      } 
     }, 
     failure: function() {     
     } 
    }); 
+0

不知道你是否看到了上述問題的評論,但它看起來像條件​​應該是'if(data.IsDataValid){...}'。我只是沒有打擾更新我的答案... –

+0

@TiesonT。是的..我更新了,謝謝 – Bob

0

解決你的問題的一部分,現在是回答的:

if(IsDataValid){ 
    // redirect to new page(
} 
else{ 
    //Show an error message without hiding the div 
} 

要重定向,使用window.location.replace('url to new page');

對於「錯誤消息」的一部分,我要麼使用jQuery UI顯示一個對話框,或者您插入錯誤信息到一個隱藏的div,也許像這樣:

$('#errors').html(data.Errors).show(); 

這裏假設你有某種名爲Errors的房產包含RegistrationModel上的驗證消息。

+0

重定向我可以使用它,但這裏的問題是我需要傳遞模型對象。 – Bob

+1

@ user1678741 - 你不能通過重定向傳遞模型對象,至少不能將其序列化爲url查詢字符串,而這可能不是你想要做的。 –

相關問題