MVC4 validation is not working even i used required - asp.net-mvc

i have this class in the model
public class Tenant :User
{
[Required]
public string PassportNumber { get; set; }
[Required]
public string image { get; set; }
[Required]
public string passportImage { get; set; }
}
in the view i have this code :
#using (Html.BeginForm("RegisterTenant", "Tenant", FormMethod.Post,
new { enctype = "multipart/form-data" })){
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.TextBoxFor(x => x.FirstName, new {placeholder = "Enter Your First Name" })
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.LastName, new { placeholder = "Enter Your Last Name"})
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Password, new { placeholder = "Enter Your Password"})
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-field">
<label>Password Again</label>
<input type="text" placeholder="Enter your password again" name="Password2"/>
<span class="errorMessage"></span>
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MobileNumber)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.MobileNumber, new { placeholder = "Enter Your Mobile Number"})
#Html.ValidationMessageFor(model => model.MobileNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PassportNumber)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PassportNumber, new {placeholder = "Enter Your Passport Number"})
#Html.ValidationMessageFor(model => model.PassportNumber)
</div>
<div class="editor-field">
<label for="file">Upload You Passport:</label>
<input type="file" name="file" id="passport" style="width: 100%;" />
<span class="errorMessage"></span>
</div>
<div class="editor-field">
<label for="file">Upload You Image:</label>
<input type="file" name="file" id="image" style="width: 100%;" />
<span class="errorMessage"></span>
</div>
<input type="submit" value="Register" class="submit"/>
}
my question
even though i used validation message and the required tag, when i press the submit button, it works though the fields are empty.
what am i doing wrong?

When you are going to use JQuery validation in a view, you have to include the required JQuery validation files in the view.
#section scripts {
#Scripts.Render("~/bundles/jqueryval")
}

Related

Uploading Image in Asp.net mvc Controller

I have a Upload form and I want to pass my information such as an Image and some other field but I don't know how can I upload Image ..
This is My model class
public partial class NewProductCategory
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
public string ProductImage { get; set; }
public string ProductQuantity { get; set; }
public Nullable<bool> ProductStatus { get; set; }
public Nullable<int> CategoryId { get; set; }
public HttpPostedFileBase user_image_data { get; set; }
public virtual Category Category { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(NewProductCategory productcategory, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
ProductCategory newproductCategory = new ProductCategory();
string path = Path.Combine(Server.MapPath("~/Content/files"), Path.GetFileName(file.FileName));
file.SaveAs(path);
newproductCategory.ProductDescription = productcategory.ProductDescription;
newproductCategory.ProductQuantity = productcategory.ProductQuantity;
newproductCategory.ProductStatus = productcategory.ProductStatus;
newproductCategory.CategoryId = productcategory.CategoryId;
db.ProductCategories.Add(newproductCategory);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", productcategory.CategoryId);
return View(productcategory);
}
And this is My View Code
#model MvcApplication1.Models.NewProductCategory
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductCategory</legend>
#using (Html.BeginForm("Create", "Temp", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
#Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductName)
#Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductPrice)
#Html.ValidationMessageFor(model => model.ProductPrice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.Label("Upload your image")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.user_image_data, new { Type = "File" })
#Html.ValidationMessageFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductQuantity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductQuantity)
#Html.ValidationMessageFor(model => model.ProductQuantity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductStatus)
#Html.ValidationMessageFor(model => model.ProductStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryId", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
<p>
<input type="submit" value="Create" />
</p>
}
</fieldset>
}
please help me in controller i am getting Null value for File upload
Update Ansawer
#model MvcApplication1.Models.NewProductCategory
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("Create", "Temp", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ #Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductCategory</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductName)
#Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductPrice)
#Html.ValidationMessageFor(model => model.ProductPrice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_image_data)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.user_image_data, new { Type = "File" })
#Html.ValidationMessageFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.Label("Upload your image")
</div>
<div class="editor-label">
#Html.TextBox("file",null,htmlAttributes: new { Type = "file" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductQuantity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductQuantity)
#Html.ValidationMessageFor(model => model.ProductQuantity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductStatus)
#Html.ValidationMessageFor(model => model.ProductStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryId", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}

using viewmodel with create view

I have a ViewModel with two models in it which works find when displaying data. My problem is I want to add a foreach() within the Create.cshtml file. Any ideas?
----Create.cshml-----
#model demo.Models.ViewModel
#{ ViewBag.Title = "Create Reference";}<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Submission Form </legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-field">
<!-- iterate through ExternalContentModel and make checkboxes. -->
#foreach (var item in Model.ExternalContentModel)
{
<label class="checkbox">
<input type="checkbox" name="users" value="#item.auth_lname"> #item.auth_lname
</label>
}
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OrganizationName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OrganizationName)
#Html.ValidationMessageFor(model => model.OrganizationName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
------Controller-----
//
// GET: /Create
public ActionResult Create() <=== can this be the problem????
{
demo.Models.ViewModel vm = new demo.Models.ViewModel();
vm.ExternalContentModel = _repository.ExternalContent();
// Return the content from the External Model to the Create.
return View(vm);
}
//
// POST: /MailingReferences/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Reference reference) <=== can this be the problem????
{
if (ModelState.IsValid)
{
db.References.Add(reference);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reference);
}
If you have different models then why don't you just create a editor templates for each model?
You can do this by creating a folder called "EditorTemplates" in the same folder your Create.cshtml view lives in. Now add a view for your model into that folder. The view should be named the same as your model class. E.g. a class called FooBarModel would have an editor template called FooBarModel.cshtml.
You would then just use the editor template by doing #Html.EditorFor(x => x.FooBar)

How auto retrieve data from database in mvc?

It is a create view page where i have insert supplier information and it is inserting data successfully. i want to get this data automatically when i will enter a name and it exist it will show all of the data in these field, if not exist then i will save to the table.
#model FCBook.Supplier
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Supplier</legend>
<div class="editor-label">
#Html.LabelFor(model => model.SupplierName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SupplierName)
#Html.ValidationMessageFor(model => model.SupplierName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNo)
#Html.ValidationMessageFor(model => model.PhoneNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Area)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Area)
#Html.ValidationMessageFor(model => model.Area)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.District)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.District)
#Html.ValidationMessageFor(model => model.District)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Division)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Division)
#Html.ValidationMessageFor(model => model.Division)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Country)
#Html.ValidationMessageFor(model => model.Country)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My controller action to this create view is
public ActionResult Create()
{
return View();
}
//
// POST: /Supplier/Create
[HttpPost]
public ActionResult Create(Supplier collection)
{
try
{
// TODO: Add insert logic here
var db = new PetaPoco.Database("FCBook");
if (collection != null)
{
collection.Insert();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I think you want to look into using Remote validation. It can be triggered after a user enters a value into one of your fields. I'm using this approach to populate other fields upon such an event occurring.

Validation stopped working on use of formmethod.post

I am trying to post external URL for eg. (www.msn.com) on press of submit button.But when I do that none of my valdation works...it simply make an entry without any data in my external url
2. Also its not going to controller when i press submit button.
I don't know if I am doing anything wrong...
Here is my code for View:
#model n.Models.PopupDemoModel
<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>
#using (Html.BeginForm("Demo","Home", FormMethod.Post, new { #action = "https://www.msn.com?encoding=UTF-8/post" }))
{
#Html.ValidationSummary(true)
<fieldset>
<input type=hidden name="oid" value="">
<input type=hidden name="retURL" value = "test" />
<input type="hidden" name="debug" value=1 />
<input type="hidden" name="debugEmail" value = "a#test.com" />
<div class="editor-label grid_2">
#Html.LabelFor(model => model.first_name)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.first_name, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.first_name)
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.email)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.email, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.email)
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.phone)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.phone, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.phone)
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.company)
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.company, new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.company)
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="grid_2 sub-spacer"> </div>
<div class="editor-field grid_2 submit">
<input type="submit" value="Submit" id="demo-submit-button"/><br />
#ViewData["DemoMessage"]
</div>
</fieldset>
Here is my model:
public class PopupDemoModel
{
[Required]
[Email]
[DisplayName("Email address")]
public string email { get; set; }
[Required]
[DisplayName("Phone number")]
public string phone { get; set; }
[Required]
[DisplayName("Contact name")]
public string first_name { get; set; }
[Required]
[DisplayName("Company name")]
public string company { get; set; }
public string MessageSent
{
get { return "We'll contact you shortly."; }
}
}
It's doing exactly what you told it to.
The HTML <form> tag sends a POST request to the URL in the action attribute.
Html.BeginForm() creates a <form> tag with an action attribute that points to your controller.
When you set the action attribute explicitly, you replace the value from MVC and make it go directly to that URL.
If you want to do something with your data on server side before posting to another website, remove the action attribute so you will be posting to the same URL as at the beggining. In the action that is handling the POST from this form and doing the validation prepare your data. When you're ready, use WebRequest class to send this data to another website using POST method.

ASP MVC3 how to add system current date?

I have form like
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
#Html.HiddenFor(model => model.CId)
<div class="editor-label">
#Html.LabelFor(model => model.CName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CName)
#Html.ValidationMessageFor(model => model.CName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Cteator)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Cteator)
#Html.ValidationMessageFor(model => model.Cteator)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.date)
#Html.ValidationMessageFor(model => model.date)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
I want to insert system current date and time in the field of Date field. How can i do this. Model and cotroller are already create by scaffolding.
Insert this before you call the editor (assuming your property is a DateTime)
#{ Model.date = DateTime.Now; }
If your property is a string, call DateTime.Now.ToString().
You could set the default value in the corresponding controller action:
public ActionResult Index() {
return View(new SomeModel { date = DateTime.Now });
}
Change your code as mention below
#{ Model.date = DateTime.Now.ToString(); }
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
#Html.HiddenFor(model => model.CId)
<div class="editor-label">
#Html.LabelFor(model => model.CName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CName)
#Html.ValidationMessageFor(model => model.CName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Cteator)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Cteator)
#Html.ValidationMessageFor(model => model.Cteator)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.date)
#Html.ValidationMessageFor(model => model.date)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>

Resources