2013-12-14 59 views
0

我有一個頁面,它有一個局部視圖(這是一個登錄表單)。點擊提交按鈕後,它會調用控制器並登錄該用戶並刷新登錄表單以顯示他已登錄。在第一個局部視圖更新後,如何刷新第二個局部視圖?

我現在需要更新顯示登錄按鈕的屏幕部分或如果他已登錄,顯示「你好,登錄用戶」

我有一個部分視圖,顯示該人是否已登錄,但我不知道如何在成功後調用它第一。我知道有一個OnSuccess事件,這似乎是我將它連接起來的地方,但我不知道如何做到這一點。

@using (Ajax.BeginForm("Login", "Account", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "loginSection", })) 
    { 
     <div id="loginSection"> 

     ...form omitted for clarity. 

     <input type="submit" value="Log in" /> 
     </div> 
    } 

這是部分視圖,需要在登錄後更新。

<ul id="menu"> 
@if (Request.IsAuthenticated) 
{ 
    <text> 
    Hello, @User.Identity.Name 
    </text> 
} 
else 
{ 
    <ul> 
     <a onclick="openLoginWindow()">Login</a> 
     <a onclick="openRegisterWindow()">Register</a> 
    </ul> 
} 

回答

0

這裏是我工作:

新增的onSuccess:

@using (Ajax.BeginForm("Login", "Account", new AjaxOptions { 
     InsertionMode = InsertionMode.Replace, 
     UpdateTargetId = "loginSection", 
     OnSuccess = "successfulLogin" 
    })) 
    {... details omitted. 

然後添加了這個:

function successfulLogin() { 
    $('#loginPartial').load('Account/LoginLinksPartial'); 

這就要求在控制器:

public ActionResult LoginLinksPartial() 
    { 
     return PartialView("_LoginLinks"); 
    } 
0

而不是使用Ajax.BeginForm的,正常使用的形式,並與您的自定義代碼做的形式發佈,這樣,你想

<div id="login"> 
@using(Html.Beginform()) 
{ 
    <input type="text" name="UserName" /> 
    <input type="text" name="Password" /> 
    <input type="submit" id="btnLogin" /> 
} 
</div> 

和腳本,你可以CONTROLL成功處理這將聽取提交按鈕單擊事件併發送表單的操作方法。

$(function(){ 

    $("#btnLogin").click(function(e){ 

    e.preventDefault(); 
    var _this=$(this); 
    var _form=_this.closest("form"); 
    $.post(_form.attr("action"),_form.serialize(),function(res){ 
     if(res.Status==="authenticated") 
     { 
      //Let's hide the login form 
      $("#login").hide(); 
      $("#yourSecondDiv").html(res.PartialViewContent); 
     } 
     else 
     { 
      alert("Wrong password"); 
     } 
    }); 

    }); 
}); 

所以javascript代碼從控制器動作

{ 
    "Status":"Authenticated", 
    "PartialViewContent" : "<p>The markup you want to show</p>" 
} 

PartialViewContent將持有你要顯示給用戶的標記期待一個JSON結構如下圖所示。

public ActionResult Login(string UserName,string Password) 
{ 
    //to do : Build the JSON and send it back 
} 

This answer將告訴你如何在一個JSON屬性發送的局部視圖的標記到客戶端。