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

时间:2022-11-30 17:56:31

I have an MVC app and want to fire up a jquery code when a view is returned from a controller.

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

This is the jquery line I have in my _Layout.cshtml (I only want this code to execute when is called by the controller, not when the page loads, I need some kind of function??)

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

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

Then in my HomeController.cs I want to call the jquery code when a user fails to authenticate or when the ModelState is not valid (I guess when the view is returned to the page).

然后在我的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**
}

Is this possible? What would be the best way to tackle this?

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

Code requested:

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 个解决方案

#1


0  

In your action method, set a variable to ViewBag which you can access in your Layout page and execute the JS as neeeded

在你的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**
}

In Layout, read this value and use that for determining whether you want to execute the js code

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

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

#2


0  

You should add a property to your user model that is returned to the view. This is a better approach than using viewbag, tempdata, etc because it allows you to have a strongly typed model.

您应该向返回到视图的用户模型添加属性。这是比使用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); 
        }
    }
}

And then in your View

然后在你的视图中

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

or

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

#1


0  

In your action method, set a variable to ViewBag which you can access in your Layout page and execute the JS as neeeded

在你的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**
}

In Layout, read this value and use that for determining whether you want to execute the js code

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

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

#2


0  

You should add a property to your user model that is returned to the view. This is a better approach than using viewbag, tempdata, etc because it allows you to have a strongly typed model.

您应该向返回到视图的用户模型添加属性。这是比使用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); 
        }
    }
}

And then in your View

然后在你的视图中

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

or

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