Custom Validation in AJAX popup in mVC - javascript

I need to perform custom validation in AJAX popup in MVC. I have created a CustomValidator and am overriding the IsValid() method. Problem lies that the popup doesn't render the custom validations properly.
My code:
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
#Styles.Render("~/Content/css")
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" />
#Scripts.Render("~/bundles/jquery")
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.ajax.unobtrusive/3.2.4/jquery.unobtrusive-ajax.min.js"></script>
#Scripts.Render("~/bundles/modernizr")
<script>
$(function () {
$("#modalDialog").dialog({
autoOpen:false,
width: 600,
height: 300,
modal: true
});
$("#opener").click(function () {
$("#modalDialog").dialog("open");
});
});
function OnSuccess(response)
{
$("#modalDialog").text(response);
}
</script>
</head>
Index.cshtml:
#model MvcPopup.Controllers.HomeController.SomeModel
#{ViewBag.Title = "Home Page";}
<p>This is page content !!!</p>
<button id="opener">Open Dialog</button>
<div id="modalDialog" title="Basic Modal Dialog">
<p>This is a basic modal dialog</p>
#using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "ID", OnSuccess = "OnSuccess" }))
{
<div>
<fieldset>
<legend>Info</legend>
#Html.LabelFor(m => m.EmailAddress)
#Html.TextBoxFor(m => m.EmailAddress)
#Html.ValidationMessageFor(m => m.EmailAddress)
<input type="submit" value="Submit" />
</fieldset>
</div>
}
</div>
HomeController.cs:
public class HomeController : Controller
{
public class SomeModel
{
[CustomValidator]
[Display(Name = "Email address")]
public string EmailAddress { get; set; }
}
public ActionResult Index()
{
var model = new SomeModel();
return View();
}
[HttpPost]
public ActionResult Index(SomeModel model)
{
if (ModelState.IsValid)
{
return PartialView();
}
return PartialView();
}
CustomValidator.cs:
public class CustomValidator : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (value.ToString().Contains("X"))
{
return ValidationResult.Success; ;
}
else
{
return new ValidationResult("Enter an email address with letter X");
}
}
else
{
return new ValidationResult("" + validationContext.DisplayName + " is mandatory.Please enter it.");
}
}
}
I can see that the Custom Validations are fired, but the render on the popup page is little bit crooked. Appears like below:
Now, I don't enter any value in the Email textbox, and click on Submit, I can see my custom validation "Email Address is mandatory. Please enter it." gets fired and is evident on the popup page as below:
I mean, its pretty evident that the custom validation should appear near to the email textbox and things should look like a popup. Please help.
EDIT
Validations appear in the popup page, but the content is somewhat crooked. I mean the content of the parent page too appear on the popup page. Snapshot below. How to get rid of it? Please help.

This is a typical and seen quite some time often. The reason that validation didn't fire is because the content like modal dialog is dynamic which is added/appeared on page later. The form validation has to parse the form again to validate the controls that are added dynamically to the page.
You have setup OnSuccess() so you can use it to parse the form.
function OnSuccess()
{
if($.validator)
{
$.validator.unobtrusive.parse("form");
}
$("#modalDialog").html(response);
}
Visit here for more info.
Note that, this solution assumes that your validation is working fine.

Related

Prevent javascript firing on load page

I have MVC application with JavaScript in the body of the cshtml page. In Model, I have a method that returns a string, and I want that string to add in some div on a page on click of a button. It works, but, the method is triggered every time I load the page (and I want it to be triggered only on click.
Here is code:
Model:
public class TestJS
{
public string Tekst1 { get; set; }
public string Tekst2 { get; set; }
public TestJS()
{
Tekst1 = "one";
Tekst2 = "two";
}
public string AddTekst()
{
return "three (additional text from method)";
}
}
Controller:
public class TestJSController : Controller
{
// GET: TestJS
public ActionResult Index()
{
Models.TestJS tjs = new Models.TestJS();
return View(tjs);
}
}
View:
#model TestJavaScript.Models.TestJS
#{
ViewBag.Title = "Index";
}
<script type="text/javascript">
function faddtekst() {
whr = document.getElementById("div3");
var t = '#Model.AddTekst()';
whr.innerHTML += t;
}
</script>
<h2>Testing JavaScript Firing</h2>
<p>
First to fields:
#Model.Tekst1;
<br />
#Model.Tekst2;
</p>
<form>
<input type="button" value="Click to show Tekst3" onclick="faddtekst()" />
</form>
<br />
<hr />
<div id="div3">
</div>
I tried to wrap JS in $(document).ready() with same result.
Somebody may think of this as a strange approach, but, a model method that I'm trying to execute takes over 10 seconds in real code, so, I want to prevent waiting every time page loads (waiting should be only if the user clicks button).
The strangest thing is that Model.AddTekst() is executed EVEN if I comment it in javascript function with '//'.
Anyone knows how to avoid unwanted execution of Model.Method?
The behavior you are experiencing is not strange at all. #Model.AddText() executes on the backend once the view is compiled which is normal behaviour.
A comment in razor would look like this
#* Comment goes here *#
But this is not what you want to achieve.
I'm afraid your approach wont work since you can't execute a method on a model asynchronously.
I suggest you take a look at Ajax.BeginForm - more info here
You could implement a controller action on the backend which would return the text you want to display on the submitting of the form.
Try to use e.preventDefault() for button click.
<form>
<input type="button" value="Click to show Tekst3" id="Show" />
</form>
Try with jQuery
$(document).on("click", "#Show", function (e) {
e.preventDefault();
faddtekst();
});

How can I generate a PartialView for each click of a button? [duplicate]

The problem I will be describing is very similar to ones I already found (e.g. this post with nearly identical name) but I hope that I can make it into something that is not a duplicate.
I have created a new ASP.NET MVC 5 application in Visual Studio. Then, I defined two model classes:
public class SearchCriterionModel
{
public string Keyword { get; set; }
}
public class SearchResultModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
}
Then I created the SearchController as follows:
public class SearchController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult DisplaySearchResults()
{
var model = new List<SearchResultModel>
{
new SearchResultModel { Id=1, FirstName="Peter", Surname="Pan" },
new SearchResultModel { Id=2, FirstName="Jane", Surname="Doe" }
};
return PartialView("SearchResults", model);
}
}
as well as views Index.cshtml (strongly typed with SearchCriterionModel as model and template Edit) and SearchResults.cshtml as a partial view with model of type IEnumerable<SearchResultModel> (template List).
This is the Index view:
#model WebApplication1.Models.SearchCriterionModel
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SearchCriterionModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Keyword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Keyword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Keyword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="btnDisplaySearchResults" value="Search" onclick="location.href='#Url.Action("DisplaySearchResults", "SearchController")'" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<div id="searchResults">
</div>
As you can see, I added a div with id="searchResults" below the standard template and edited the button. What I want is to display the partial view SearchResults.cshtml in the div on the bottom, but only after the button is clicked. I have succeeded in showing a partial view there by using #Html.Partial("SearchResults", ViewBag.MyData), but it is rendered when the parent view is loaded for the first time and I set ViewBag.MyData in the Index() method already, which is not what I want.
Summary: On clicking the button, I will obtain some List of SearchResultModel instances (via database access) and then the partial view should be rendered, using this newly obtained data as model. How can I accomplish this? I already seem fail at the first step, that is reacting to the button click with the above code. Right now, I navigate to the URL ~/Search/DisplaySearchResults, but of course there's nothing there and no code-behind method is called.
In traditional ASP.NET I'd just have added a server-side OnClick handler, set the DataSource for a grid and show the grid. But in MVC I already fail with this simple task...
Update: Changing the button to #Html.ActionLink I can finally enter the controller method. But naturally since it returns the partial view, it's displayed as the whole page content. So the question is: How do I tell the partial view to be rendered inside a specific div on the client side?
Change the button to
<button id="search">Search</button>
and add the following script
var url = '#Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})
and modify the controller method to accept the search text
public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}
The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.
Side note: The use of a <form> tag and #Html.ValidationSummary() and #Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.
Edit
Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event
<input type="submit" value="Search" />
var url = '#Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})
and the controller method would be
public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}
So here is the controller code.
public IActionResult AddURLTest()
{
return ViewComponent("AddURL");
}
You can load it using JQuery load method.
$(document).ready (function(){
$("#LoadSignIn").click(function(){
$('#UserControl').load("/Home/AddURLTest");
});
});
source code link

how to create an alert prompt in the controller before redirecting to a new view?

is it possible to create an alert prompt in the controller before redirecting to a new view? i want to make the users acknowledge a message in the current view before directing them to the next view
using System.Web.Mvc;
using System.Web.Security;
using MvcApplication.Models;
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
***// Here! create an alert with a close button using javascript and make the user acknowledge it by clicking a button and closing the alert before redirecting the user***
if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return this.Redirect(returnUrl);
}
return this.RedirectToAction("Index", "Home");
}
this.ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");
return this.View(model);
}
Return from that method some View with the message, with a link and/or an auto-redirect.
It's not possible to "pause" the processing of the controllers to send messages back to the user!!
Make a custom ActionFilter and put this action filter on Controller's Action
public class CustomActionFilter : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.StartupScript = "Your Message Goes here";
base.OnActionExecuted(filterContext);
}
}
Your javascript code on _Layout page as below
<script type="text/javascript" defer="defer">
alert('#Html.Raw(ViewBag.StartupScript)');
</script>
You controller Action
[CustomActionFilter]
public ActionResult Helo(
{
//Some Stuff here
}
Yes it possible to show (javascript)alert box from controller.
Just add below line to your controller.
Try with this it may help you.
return JavaScript(alert("Hello this is an alert"));
You can add it by using ViewBag in MVC. You could put your javascript code in a ViewBag like:
ViewBag.Javascript = "<script language='javascript' type='text/javascript'>alert('Your message');</script>";
and then navigate to your page.

Hidden value not being set by jQuery?

I'm following along with an example from a Pluralsight class on Single Page in MVC and the instructor is using a hidden field to hold the "mode" the page is in. When the user click's the Add button it should set the "EventCommand" using some jQuery. However, I can't get mine to set.
Looking in the dev tools I don't see any errors. When I set some alerts inside the jQuery they will fire off so I know the jQuery is being called. When I veiw the page source I can see and input field with an a name of "EventCommand". It looks like it should be setup correctly but it's not setting the hidden field.
Anyone have an idea why this wouldn't be working?
ViewModel showing the properties as well as the HanndleRequest() which looks at the EventCommand to decide what to do but is NULL when the add button is clicked.
public string Mode { get; set; }
public string EventCommand { get; set; }
public string EventArgument { get; set; }
public void HandleRequest()
{
switch (EventCommand.ToLower())
{
case "list":
GetCalls();
break;
case "add":
Add();
break;
case "edit":
IsValid = true;
Edit();
break;
}
}
Top of View that has the HiddenFor and the Add button.
#using (Html.BeginForm())
{
<!-- BEGIN HIDDEN FIELDS AREA -->
#Html.HiddenFor(m => m.EventCommand)
#Html.HiddenFor(m => m.Mode)
#Html.HiddenFor(m => m.EventArgument)
<!-- END HIDDEN FIELDS AREA -->
<button id="btnAdd" class="btn btn-sm btn-success" data-cpp-action="add">
<i class="glyphicon glyphicon-plus"></i> Create New
</button>
jQuery that is at the bottom of the View. I get the alert that the click event happened but the alert with the data-cpp-action says undefined.
#section scripts {
<script>
$(document).ready(function () {
$("[data-cpp-action]").on("click", function (e) {
e.preventDefault();
alert("in click");
alert("action: " + $(this).data("data-cpp-action"));
$("#EventCommand").val(
$(this).data("data-cpp-action"));
$("#EventArgument").val(
$(this).attr("data-cpp-val"));
$("form").submit();
});
});
</script>
}
No need for the "data" in the data function. Only use "cpp-action":
<script>
$(document).ready(function() {
$("[data-cpp-action]").on("click", function(e) {
e.preventDefault();
alert("in click");
alert("action: " + $(this).data("cpp-action"));
$("#EventCommand").val($(this).data("cpp-action"));
$("#EventArgument").val($(this).attr("cpp-val"));
$("form").submit();
});
});
</script>
Also see the jQuery documentation: https://api.jquery.com/data/
Change
$(this).data("data-cpp-action"));
for
$(this).attr("data-cpp-action"));
This is why: jQuery Data vs Attr?

NullReferenceException in embeded if clause

I am currently trying to program a forgot password page where the user enter their username, their email address and a message which will be sent to the administrator of the site.
Want I want is the following:
After the user clicks on the button the username and the email address should be checked if they are associated. (Those values are saved in my database)
I managed to programm everything but I have a problem which I cannot solve.
Everytime the Razor engine renders the page I'll get a NullReferenceException was unhandled by user code.
I know why this is happening but as I said I cannot fix this.
Here is the code:
#model MvcApplication1.ViewModels.ContactAdminViewModel
#using MvcApplication1.Queries
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" />
<title>SendMail</title>
</head>
<body>
#using (Html.BeginForm("SendMail", "ContactAdmin", FormMethod.Post))
{
#Html.ValidationSummary(true)
<div>
<p>
#Html.LabelFor(m => m.username, "username")
#Html.EditorFor(m => m.username)
<p>
#Html.ValidationMessageFor(m => m.username)
</p>
</p>
<p>
#Html.LabelFor(m => m.email, "email")
#Html.EditorFor(m => m.email)
<p>
#Html.ValidationMessageFor(m => m.email)
</p>
</p>
<p>
#Html.LabelFor(m => m.message, "Your message")
<p>
#Html.TextAreaFor(m => m.message, new { cols = "35", rows = "10", #style = "resize:none" })
<p>
#Html.ValidationMessageFor(m => m.message)
</p>
</p>
</p>
<p>
<input id="send-mail" type="submit" class="button" value="Send" />
</p>
</div>
<script type="text/javascript">
$(document).ready(function () {
jQuery('#send-mail').click(function () {
#if (#DQL.CheckUsernameAndEmail(Model.username, Model.email))
{
<text>
alert("Your Message will be sent");
</text>
}
else
{
<text>
alert("Your username is not associated with the email adress");
</text>
}
});
});
</script>
}
</body>
</html>
Any tips on how to solve that problem are highly appreciated :)
EDIT
The DQL.cs is a C# Class where I wrote down all my queries.
It's actually the model that is null. I forgot to write that :/ I'm really sorry.
Nevertheless here is the code from the DQL.cs which checks if the username is associated with the email address:
public static bool CheckUsernameAndEmail(string username, string email)
{
bool validateUser = false;
var query = from u in db.User
where (u.email.Equals(email) && u.username.Equals(username))
select u;
if (query.Count() != 0)
validateUser = true;
return validateUser;
}
This the Controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.ViewModels;
using MvcApplication1.Database_Queries;
namespace MvcApplikation1.Controllers
{
public class ContactAdminController : Controller
{
[HttpGet]
public ActionResult SendMail()
{
return View();
}
[HttpPost]
public ActionResult SendMail(ContactAdminViewModel contactAdmin)
{
if (ModelState.IsValid)
{
if (DQL.CheckUsernameAndEmail(contactAdmin.username, contactAdmin.email))
{
MvcApplication1.Mail.SendMail.SendForgotPassword(contactAdmin.username, contactAdmin.email, contactAdmin.message);
return RedirectToAction("LogIn", "Account");
}
}
else
{
ModelState.AddModelError("", "Your username is not associated with the email adress");
return RedirectToAction("LogIn", "Account");
}
return RedirectToAction("LogIn", "Account");
}
}
}
If this is getting a NullReferenceException:
if (#DQL.CheckUsernameAndEmail(Model.username, Model.email))
Then it's either because DQL is null, Model is null, or some code in CheckUsernameAndEmail is throwing that exception. We don't have enough context in this question to know what DQL is, and the population of your model is done in your controller action, which is not posted in this question. Posting CheckUsernameAndEmail's code may also help.
Basically, any time you get NullReferenceException it means you have a null reference.
Update
Thanks for the updated information! If you don't want your Model to be null when executing your Razor view, make sure to add a model to your ViewResult:
[HttpGet]
public ActionResult SendMail()
{
var model = new ContactAdminViewModel();
// Populate your model with the appropriate data
return View(model);
}

Categories