I have an MVC app and want to fire up a jquery code when a view is returned from a controller.
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??)
<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).
[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>
In your action method, set a variable to ViewBag which you can access in your Layout page and execute the JS as neeeded
[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
<script type="text/javascript">
$(function(){
var shouldExecuteJs="@ViewBag.ShouldExecuteJs";
if(shouldExecuteJs)
{
$("#drpdown").addClass("open");
}
});
</script>
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.
[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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.