更新第一个局部视图后,如何刷新第二个局部视图



我有一个部分视图的页面(它是一个登录表单)。当点击提交按钮时,它会调用控制器并将人员登录,并刷新登录表单以显示他已登录。

我现在需要更新屏幕上显示登录按钮的部分,或者如果他登录了,则显示"Hello,logged in user"

我写了一个部分视图,显示这个人是否登录,但我不知道在第一个成功后该如何称呼它。我知道有一个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>
}

不要使用Ajax.BeginForm,而是使用普通表单,并使用自定义代码进行表单发布,这样您就可以随心所欲地控制成功处理程序

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

以及将监听提交按钮点击事件并发送表单的操作方法的脚本。

$(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代码期望控制器动作产生如下JSON结构

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

CCD_ 2将保存要向用户显示的标记。

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

这个答案将告诉您如何将JSON属性中的部分视图的标记发送到客户端。

以下是对我有效的方法:

添加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");
    }

最新更新