从Controller ASP.NET MVC返回View时调用jquery代码

时间:2015-10-22 19:13:33

标签: jquery asp.net asp.net-mvc

我有一个MVC应用程序,并希望在从控制器返回视图时启动jquery代码。

这是我在_Layout.cshtml中的jquery行(我只希望这个代码在被控制器调用时执行,而不是在页面加载时,我需要某种函数吗?)

<script>
    $("#drpdown").addClass("open");
</script>

然后在我的HomeController.cs中,我想在用户无法进行身份验证或ModelState无效时调用jquery代码(我猜想当视图返回到页面时)。

[HttpPost]
public ActionResult Index(UserAccount user)
{
    if (ModelState.IsValid)
    {
        //Authenticate User
        ...
        //User Failed to Authenticate
        ...
        return View(user); //**FIRE UP JQUERY**
    }

    return View(user); //**FIRE UP JQUERY**
}

这可能吗?解决这个问题的最佳方法是什么?

请求的代码

UserAccount.cs

namespace ProfessionalDev.Models
{
    public class UserAccount
    {
        [Required(ErrorMessage = "Required Field")]
        public string email { get; set; }

        [Required(ErrorMessage = "Required Field")]
        public string password { get; set; }

        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }

        public bool AddOpenClass { get; set; }

        public UserAccount() { }
    }
}

HomeController.cs

[HttpPost]
public ActionResult Index(UserAccount user)
{
    if (ModelState.IsValid)
    {
        //Authenticate User

        //User Failed to Authenticate
        user.AddOpenClass = true;
        TempData["alert"] = "alert-danger";
        TempData["error"] = "Email or Password Incorrect";
    }

    user.AddOpenClass = true;
    return View(user);
}

_Layout.cshtml

@model ProfessionalDev.Models.UserAccount

<!DOCTYPE html>
<html>
<head>
...
<ul class="nav navbar-nav navbar-right">
    <li><a href="#">New User</a></li>
    <li class="dropdown" id="drpdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Log In <span class="caret"></span></a>
        <ul class="dropdown-menu">
            <li>
                @Html.Partial("_Errors")

                @using (Html.BeginForm("Index", "Home", FormMethod.Post))
                {
                    @Html.ValidationMessageFor(model => model.email)
                    @Html.TextBoxFor(model => model.email, new { @class = "form-control", @placeholder = "Email" })

                    @Html.ValidationMessageFor(model => model.password)
                    @Html.PasswordFor(model => model.password, new { @class = "form-control", @placeholder = "Password" })

                    <input type="submit" value="Submit" class="btn btn-primary" />
                }
            </li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Forgot Password?</a></li>
        </ul>
    </li>
</ul>
...
    @if (Model.AddOpenClass)
    {
    <script>
       $(function(){
            $("#drpdown").addClass("open");
       });
    </script>
    }

</body>
</html>

2 个答案:

答案 0 :(得分:0)

在你的action方法中,将一个变量设置为ViewBag,你可以在Layout页面中访问它并按需要执行JS

[HttpPost]
public ActionResult Index(UserAccount user)
{
    ViewBag.ShouldExecuteJs = true;
    if (ModelState.IsValid)
    {
        //Authenticate User
        ...
        //User Failed to Authenticate
        ...
        return View(user); //**FIRE UP JQUERY**
    }
    return View(user); //**FIRE UP JQUERY**
}

在布局中,读取此值并使用它来确定是否要执行js代码

<script type="text/javascript">
   $(function(){
      var shouldExecuteJs="@ViewBag.ShouldExecuteJs";
      if(shouldExecuteJs)
      {
        $("#drpdown").addClass("open");
      }
   });
</script>

答案 1 :(得分:0)

您应该向返回到视图的用户模型添加属性。这是比使用viewbag,tempdata等更好的方法,因为它允许你有一个强类型模型。

[HttpPost]
public ActionResult Index(UserAccount user)
{
    if (ModelState.IsValid)
    {

        //User Failed to Authenticate
        if(auth.failed)
        {
            //You might have a property specifically for authentication like this:
            user.failedToAuthenticate = true;

            // Or you could have a generic error message property that you display when not null
            user.errorMessage = "Authentication Failed!";

            return View(user); 
        }
    }
}

然后在您的视图中

 @if(Model.failedToAuthenticate)
 {
    // Fire your jQuery
    <div class="alert-danger">@Model.errorMessage</div>
 }

or

@if(!string.IsNullorEmpty(Model.errorMessage))
{
    //Display error message
}