Ajax Form Validation Messages don't show - asp.net-mvc

This is for the first time I'm working on validations in Asp.Net MVC-4.
The problem here is that the validation messages don't show for the
required fields even when I post an empty form.
This is the form I'm using:
#using (Ajax.BeginForm("Save","DSA",
new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
#Html.TextBoxFor(m => m.Insert_DSA.DSAId)
#Html.ValidationMessageFor(m => m.Insert_DSA.DSAId)
#Html.TextBoxFor(m => m.Insert_DSA.Firstname)
#Html.ValidationMessageFor(m => m.Insert_DSA.Firstname)
<input type="submit" value="Save" />
}
And in the Model Class:
[Required(ErrorMessage = "DSA ID is required")]
public string DSAId { get; set; }
[Required(ErrorMessage = "First Name is required")]
public string Firstname { get; set; }
And this is the controller:
public ActionResult Save(Models.clsDSAMaster MyModel,string submit)
{
string data = "";
if (ModelState.IsValid)
{
MyModel.Insert_DSA.addDSA(MyModel.Insert_DSA, Session["EmpCode"].ToString());
data="success";
}
else
{
data="Faliure";
}
return Content(data, "text/html");
}
Can anyone please help me get it to work and enlighten me a little on how validations work in MVC.
P.S : The model binding and the data retrieval from the model on the form submit is working perfectly.

You have to enable unobtrusive JavaScript. You can do it in the configuration file:
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
or you can also turn it on form the code:
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

Related

Validation in model not firing

Driving me crazy.... validation not firing.
When I leave the field blank and hit submit it behaves as if the model were valid.
I have used dbFirst entity framework to create the model and added the required data annotation after the fact.
My Model (Entity)
public partial class Certificate
{
public Certificate()
{
this.Travelers = new HashSet<Traveler>();
}
public int ID { get; set; }
public System.DateTime InsertDate { get; set; }
[Required(ErrorMessage = "Please enter your card number.")]
public string CertificateNumber { get; set; }
public Nullable<int> BuyerID { get; set; }
public string Used { get; set; }
public string Active { get; set; }
public virtual ICollection<Traveler> Travelers { get; set; }
}
My Controller:
[HttpPost]
public ActionResult Index(Certificate CertificateNumber)
{
if (ModelState.IsValid)
{
return RedirectToAction("Create", "Travelers");
}
return View();
}
My View:
#model GrandCelebration.Models.Certificate
#{
ViewBag.Title = "Validation";
}
<div>
<h2>Please enter your card number below to validate</h2>
<div id="searchbar">
#using (Html.BeginForm())
{#Html.ValidationSummary(true)
<fieldset>
#Html.TextBoxFor(model => model.CertificateNumber)
<input type="submit" class="btn" alt="Validate" style="display:inline" value="Validate" />
#Html.ValidationMessageFor(model => model.CertificateNumber)
</fieldset>
}
</div>
</div>
The problem was that the required js files weren't included.
Firstly make sure that unobtrusive validation is enabled in Web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
Then include 3 js files in the _Layout page:
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
When cient-side validation is successfully enabled, if you look at the textbox HTML you will see a data-val property has been added.

mvc dropdownlst initial value

I have a drop down list in MVC
Model:
[Required]
[Display(Name = "State of Residency:")]
public string StateCode { get; set; }
My View:
#Html.DropDownList("StateCode", "Select")
#Html.ValidationMessageFor(model => model.StateCode)
The drop down list works fine but how to make the validator validate the select. So it say please select a value in Select is there.
Example for ASP.NET MVC 5 web application:
In your case I would make like so:
1) Enable validation in web.config
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
2) add proper jQuery files
<script src="~/Scripts/jquery-1.11.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script> <!--v1.13.0-->
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> <!-- For ASP.NET MVC 5.0 -->
3) StateCode.cs
public class StateCode
{
public int Id { get; set; }
public int Code { get; set; }
}
4) MyModel.cs
public class MyModel
{
[Required(ErrorMessage = "Please select")]
public int IdSelected { get; set; }
[Display(Name = "State of Residency:")]
public IEnumerable<StateCode> StateCodes { get; set; }
}
5) Action
[HttpGet]
public virtual ActionResult Index()
{
var model = new MyModel
{
StateCodes = new List<StateCode>
{
new StateCode{Id=1, Code=22333},
new StateCode{Id=2, Code=44433},
new StateCode{Id=3, Code=55533},
}
};
return View(model);
}
6) View
#model MyModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.IdSelected, new SelectList(Model.StateCodes, "Id", "Code"), "Please Select")
#Html.ValidationMessageFor(model => model.IdSelected)
<input type="submit" value="OK" />
}
btw. here very good list of jQuery files for ASP.NET MVC unobtrusive validation.

Data validation not working in view (DataAnnotations)

I'm having trouble getting data validation working in my view.
I believe 'AssetName' should show an error message if a user tabs into the textbox and doesn't put any data in but no message is shown when the textbox loses focus.
Model:
using System.ComponentModel.DataAnnotations;
namespace ACore.Models
{
public class AssetForm
{
[Required]
public string AssetName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
[UIHint("StatesEditor")]
public State State { get; set; }
[Required(ErrorMessage = "TEST")]
public string ZipCode { get; set; }
[Required]
public string Seg3Code { get; set; }
}
}
View:
#using System.Web.Optimization
#model ACore.Models.AssetForm
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "frmAsset" }))
{
<div class="tempStyle">
<div class="editor-label fl">
#*#Html.LabelFor(model => model.AssetName)*#
Asset Name:
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetName)
#Html.ValidationMessageFor(model => model.AssetName)
</div>
</div>
<div class="tempStyle">
<div class="editor-label">
Address 1:
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address1)
#Html.ValidationMessageFor(model => model.Address1)
</div>
</div>
}
Section of Web.config
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="true" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
I ended up adding the code below but it appears that the DataAnnotations in my class have no bearing on the validation. I would prefer to control the validation through DataAnnotations:
// Validate the Maintenance and Office percentages.
var validator = $("#frmAsset").validate({
rules: {
AssetName: {
required: true
},
Seg3Code: {
required: true,
minlength: 3,
maxlength: 3
}
},
messages: {
AssetName: " ✖ Required",
Seg3Code: " ✖ Required"
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "/Asset/Create",
data: {
},
//data: $("form").serialize(),
success: function (data) {
//console.log(data);
// Close popup window
var window = $('#AssetEditorPopUp').data("kendoWindow");
window.close();
// Refresh grid to show changes
$('#grid').data("kendoGrid").dataSource.read();
},
error: function () {
alert("There was an error editing the asset.");
}
});
return false; // to block page redirect since you're using ajax
}
In you BeginForm there is no posting action that is causing Submit and hence call validation. This is required unless you have some Javascript code that validate on tab-out.
In your using code block add
<input type="submit" value="textOnSubmitButton" />
and provide action and controller in BeginForm function to handle action on posting of form in the controller.
Add this in your controller
[HttpPost]
public ActionResult theAction(){
return View();
}
You will get error message on click of the submit button

ASP.NET MVC Unobtrusive client validation not working

In my ASP.NET MVC 4 application I am trying to use unobtrusive client validation with Fluent Validation.
<script src="/Scripts/jquery.validate.min.js" type="text/javascript">
</script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript">
</script>
I have these two .js files that VS2010 provides when new ASP.NET MVC 4 application is created. I have also enabled client side validation on my web.config file.
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
As far as I know when client validation and unobtrusive JavaScript is enabled, input fields with a client-validation rule contain the data-val="true" attribute to trigger unobtrusive client validation. And I have these field on my input fields.
For instance,
<input class="input-validation-error" data-val="true" data-val-
required="error text here" id="purchasePrice"
name="PurchasePrice" type="text" value="">
<span class="field-validation-error error" data-valmsg-for="PurchasePrice"
data-valmsg-replace="true">'Purchase Price' must not be empty.</span>
However, when I submit my form, it is posted to controller and my model is checked on my controller code instead of client side.
EDIT :
This is my form opening tag.
#using (Html.BeginForm("Create", "Product", FormMethod.Post,
new { enctype = "multipart/form-data", #class = "mainForm",
#id = "productCreateForm" }))
Any ideas? Thanks.
Did you add the configuration for MVC?
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// this line is required for fluent validation
FluentValidationModelValidatorProvider.Configure();
}
You also need to configure each view model / validator:
[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
If this does not help, could you post an example of a validator that is not working correctly? Not all validation can be done client side. For example, the following validator will only work server side:
// when validator rules are always server side
public class ServerSideValidator : AbstractValidator<Person> {
public ServerSideValidator() {
When(x => x.Name == "Foo", () => {
RuleFor(x => x.Email).EmailAddress();
});
}
}

MVC client side validation with subproperties

Having the following classes:
public class MyObjB {
[Required(ErrorMessage = "I need it")]
public string Name { get; set; }
}
public class MyObjA {
[Required(ErrorMessage = "I need it")]
public string Name { get; set; }
public MyObjB MyObjB { get; set; }
}
The View: using the model as MyObjA
#{ Html.EnableClientValidation(); }
#{Html.BeginForm();}
#Html.ValidationSummary("Some errors") #Html.AntiForgeryToken()
// MyObjA part
#Html.LabelFor(model => model.Name):
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessage("Name", "*")
// MyObjB part
#Html.LabelFor(model => model.MyObjB.Name):
#Html.TextBoxFor(model => model.MyObjB.Name)
#Html.ValidationMessage("MyObjB.Name", "*")
#{ Html.EndForm(); }
The EnableClientValidation will not work....
I think this is related with the "." (dot) used and problems with the javacript, but I can be wrong and the cause be different.
If I do the same form but only for the MyObjB, it will work fine and the ClientValidation is done correctly.
How do you people use EnableClientValidation with subproperties?
Thank you.
EDIT 1 - For byte request
View:
#Html.TextBoxFor(model => model.MyObjB.Name)
HTML Result:
<input id="MyObjB_Name" name="MyObjB.Name" type="text" value="" />
I think you must use following in you web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
It will work as long as you have the reference and initialization of objB in objA, because your model to the view is ObjA
what you need to do is create a viewmodel for your view
which will have properties of Class A and Class B
public class ViewModelAB
{
[validation error message]
A PropertyA { get; set; }
[validation error message]
B PropertyB { get; set;}
}
and use this viewmodel model strogly types to your view

Resources