Data validation not working in view (DataAnnotations) - asp.net-mvc

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

Related

Ajax Form Validation Messages don't show

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;

How to Upload file In MVC + Umbraco 7

I am new to MVC and need help to upload File , I am using umbraco. 7.2.1
I am trying to send mail with mail with attachment
Following is my code for the same.
Partial View ==>name Contact
using (Html.BeginUmbracoForm<ContactVController>("HandleContactSubmit"))
{
#Html.LabelFor(model => model.Name)<br />
#Html.EditorFor(model => model.Name)<br />
#Html.ValidationMessageFor(model => model.Name)<br />
#Html.LabelFor(model => model.Email)<br />
#Html.EditorFor(model => model.Email)<br />
#Html.ValidationMessageFor(model => model.Email)<br />
<input type="file" name="file" id="file" />
<p>
<input type="submit" value="Submit" />
</p>
}
Model
public class ContactVModel
{
[Required]
public string Name { get; set; }
[Required]
[RegularExpression(#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")]
public string Email { get; set; }
[Required]
public string Message { get; set; }
public HttpPostedFileBase attachment { get; set; }
}
Controller
public class ContactVController : SurfaceController
{
[HttpPost]
public ActionResult HandleContactSubmit(ContactVModel model)
{
,.......... ...... ....
,.......... ...... ....
MailBody + = model.Name ;
MailBody + = model.Email;
SendMail( MailBody )
}
But I do not know access model.attachment , How can I do so to send mail with attachment (the file which is uploaded ) (As I am able to acces Name, Email, etc.)
I have referred following post but I could not able to access attachment
MVC 4 Razor File Upload
but I could not make it out
Change the input from
<input type="file" name="file" id="file" />
to
<input type="file" name="attachment" id="attachment" />
So the property in the model matches the input field.
I'm currently using the following:
In the cshtml file:
#Html.UploadFor(model=> model.Attachment)
static public class HtmlExtensions
{
public static IHtmlString UploadFor<TSource, TResult>(this HtmlHelper<TSource> html, Expression<Func<TSource, TResult>> propertyExpression)
{
var memberName = Reflection.GetPropertyName(propertyExpression);
return new HtmlString($"<input type=\"file\" name=\"{memberName}\" id=\"{memberName}\">");
}
}
class Reflection
{
public static string GetPropertyName<TSource, TResult>(Expression<Func<TSource, TResult>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
}

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.

posting data from partial view on main view then submitting to controller

I have a MVC model as follows
public class ListSampleModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int SampleId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public IList<PointOfContact> lstPoc { get; set; }
}
public class PointOfContact
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int PocID { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
}
What I have done is, create "PointOfContact" as a partial view on a jquery dialog and on "save" button click it shows the data on the main view in labels (I will have multiple point of contacts), now on submit I want this data along with the property values of ListSampleData to be posted back to the controller.
The issue is, the data related to simple properties are returned back but the list is always null.
below is my View
#model MVCDataFlowSample.Models.ListSampleModel
#using (Html.BeginForm("Create", "ListSample", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ListSampleModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div id="dialog1" class="ui-dialog" style="background-color:gray;"></div>
<div id="data">
</div>
<p>
<input type="button" value="Add More..." id="btnAdd" />
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Javascript on Main View
<script type="text/javascript">
$(document).ready(function () {
$('#btnAdd').on('click', function () {
$('#dialog1').dialog({
autoOpen: true,
position: { my: "center", at: "center", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('#Url.Action("PocPartial", "ListSample")');
},
buttons: {
"Save User": function () {
addUserInfo();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
return false;
});
function addUserInfo(email, phone) {
var text = "<div id='EmailAddress'>Email Address:" + $("#EAddress").val() + "</div><div id='PhoneNumber'>Phone Number:" + $("#PhNo").val() + "</div>";
$("#data").append(text);
}
});
</script>
Partial View
#model MVCDataFlowSample.Models.PointOfContact
<div>
#Html.Label("EmailAddress:")
<div>
#Html.TextBoxFor(x => x.EmailAddress, new { id = "EAddress" })
</div>
#Html.Label("PhoneNumber:")
<div>
#Html.TextBoxFor(x => x.PhoneNumber, new { id = "PhNo" })
</div>
</div>
any help will be appreciated.
The contents of DIV elements are not submitted as form data. If you'd like that data to be submitted, add it to the DOM as hidden INPUT elements in addition to your DIVs. You'll also need to format their names correctly so that MVC knows how to bind them. See this article for how complex objects are bound in MVC.
I posted partial view data to the main page's post action You can modify the idea to any of your suits
Partial View
<select name="Country">
<option>Indian</option>
<option>Africa</option>
</select>
<select name="State">
<option>Kerala</option>
<option>TamilNadu</option>
</select>
<select name="City">
<option>Thrissur</option>
<option>Palakkad</option>
</select>
Index Page
#{
ViewBag.Title = "IndexTestPost";
}
<h2>IndexTestPost</h2>
#using(Html.BeginForm()){
#Html.Partial("~/Views/_PartialPagePostCountry.cshtml");
<input type="submit" />
}
Class To Catch Post Data
public class CountryCityState
{
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
}
Controller
public class TestPostPartialController : Controller
{
// GET: TestPostPartial
public ActionResult IndexTestPost()
{
return View();
}
[HttpPost]
public ActionResult IndexTestPost(CountryCityState CtnCtySta)
{
return View();
}
}

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.

Resources