check empty or invalid properties - asp.net-mvc-4

I have a model with validation properties. On a post back to server I would like to check if model values are empty or for example dropdownlist should not be have 0 or something!

Depending on how you have created your models you could do the validation on he model properties.
Example:
public class Foo
{
public long Id { get; set; }
[Required(ErrorMessage = "Please enter name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please select a gender")]
public string SelectedGenderId{ get; set; }
}
Then in your view under your dropDownList:
#Html.ValidationMessageFor(m=> m.SelectedGenderId)
EDIT thanks to #danludwig:
Then in your controller you can validate the state of your model but doing this:
if (ModelState.IsValid)
{
// do your updates/saves
}
I hope that's is what you are after.

Related

Clear ViewModel validation Error

I have created a ViewModel which contains other models
namespace CreatingLayout.Models
{
public class ViewModel
{
public tbl_Roles Roles { get; set; }
public tbl_Category Category { get; set; }
public tbl_Course Course { get; set; }
public tbl_User User { get; set; }
}
}
And this sub Model has some Required Field field like tbl_User class has following required fields:
public partial class tbl_User
{
[Required(ErrorMessage = "Please enter {0}")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter {0}")]
public string Password{ get; set; }
//And many more with Required Field
}
Now my problem is, in my View i am not passing data for all this required fields but only for few. So once i click to submit button, i am calling my Controller Action Method and i am checking for ModelState errors
public ActionResult AdminInsertion(ViewModel objViewModel)
{
if (ModelState.IsValid)
{
//IF No Errors do something
}
return View();
}
So everytime my Modelstate.Isvalid is returning false due to Validation Error which i gave in those 4 classes i.e., tbl_Roles, tbl_Category, tbl_Course and tbl_User. So what i want is to Clear all those error for which i am not passing Data, something like
//Here i want to go to individual classes ex: item should contains all tbl_Roles column fields
foreach(var item in ModelState.Keys)
{
//Now i want to Get Key items of each individual class which is causing Error
foreach(string Key in item)
{
//Here i am going to clear all those error for which i am not passing data
ModelState[Key].Error.Clear();
}
}
But my problem is, i am not able to access fields of tbl_Roles, tbl_Category, tbl_Course and tbl_User. ,How can clear only selected field errors here?

asp.net MVC: TryUpdateModel doesn't bind DateTime properly

I'm having issues with a date property not binding correctly using TryUpdateModel in MVC.
I am using a POCO class and a corresponding viewModel.
public class ContactModel
{
public int Id { get; set; }
[Display(Name = "First Name")]
[StringLength(50)]
[Required(ErrorMessage = "First name must be entered.")]
public string ContactGivenName { get; set; }
[Display(Name = "Last Name")]
[StringLength(50)]
[Required(ErrorMessage = "Last name must be entered.")]
public string ContactFamilyName { get; set; }
....
[Display(Name = "Date of Birth")]
public DateTime? DateOfBirth { get; set; }
}
the entity class:
public class Contact
{
[Key]
public int Id { get; set; }
[StringLength(50)]
[Column(TypeName = "varchar")]
public string ContactFamilyName { get; set; }
[StringLength(50)]
[Column(TypeName = "varchar")]
public string ContactGivenName { get; set; }
...
[Column(TypeName = "date")]
public DateTime? DateOfBirth { get; set; }
}
and in my controller :
[HttpPost]
[GridAction]
public virtual ActionResult UpdateContact(int id, FormCollection form)
{
//Find a customer whose CustomerID is equal to the id action parameter
var c = _contactService.Get(id);
if (c != null)
{
//Perform model binding (fill the customer properties and validate it).
if (TryUpdateModel(c, form))
{
The _contactService.Get returns the instance from EntityFramework.
The TryUpdateModel binds string properties like first and last name correctly, but despite a lot of tries, I can't get it to bind the date of birth.
I suspect it's a formatting issue of some kind but cannot find what it is.
When I debug, I can see in the FormCollection that the date is correctly there, with the value that was input in the view so the data is definitely passed on to the controller.
the value passed to the controller is in format :
yyyy-MM-dd
I tried modifying this on the fly with multiple format without success.
Any ideas what I'm doing wrong here ?
Thanks a lot
Well, first, I have no idea why you're using TryUpdateModel.. That's pretty archaic.
Second, it sounds to me like you have not set your culture to accept the format you expect. Add the following to your web.config if your browser is defaults already set to the correct culture:
<system.web>
<globalization culture="auto" uiculture="auto" enableclientbasedculture="true">
</globalization>
</system.web>
If you want to force a culture, then set the culture you wish in this setting.
the globalization didn't help and is actually already set, however I realized there's a custom binder for Datetime and that is probably where my problem is.
thanks

Required field is not working in mvc4

in my model i have email, password,new password and re-type new password property's are there.
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email: ")]
public string Email { get; set; }
public bool changePassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Old Password:*")]
public string OldPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "New Password:*")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Re-type Password:*")]
i put required to all controls.
in my view i devide those controls like, Email in one form and remaining are another form. my problem is email validation is working in form form.
coming to another form validation is not working.
can any one suggest me to come out this problem.
in your cshtml file say layout try putting this
#Scripts.Render("~/Scripts/jquery.validate.min.js")
#Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
this might work.
Make sure that you are submitting to proper controller and using the ModelState.IsValid
// POST: /Orders/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Orders order) {
if (ModelState.IsValid) {
try {
.....

SelectList when using EditorFor

i have come across a strange behaviour when trying to get a SelectList to display correctly when using the Html.EditorForModel().
I have the following Model:
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
public string Gender { get; set; }
[UIHint("SelectList")]
public SelectList AvailibleGender { get; set; }
}
As you can see, I have a SelectList item that holds the values to get put into the Gender string. I have overriden the SelectList EditorTemplate, which for now has a simple script tag showing an alert box.
When I use EditorFor(m=>AvailableGender), my alert box fires, which means the editor correctly chose my SelectList template.
When I use EditorForModel(), my alert box does not fire.
If I change the model as follows:
[UIHint("SelectList")]
public string AvailibleGender { get; set; }
..then my SelectList template does get hit, and I see the alert message.
So it looks like there is something specifically blocking the SelectList.
In case it is something to do with specific custom types, I tried adding an object.cshtml file, but this doesn't get invoked either. so it seems that the SelectList type is getting lost somewhere.
Does anyone have any ideas on how to get the Select List working with EditorForModel()?

How do I preseve an object type member inside an ASP.Net MVC view?

Here are my two classes:
class Company
{
public int ID{ get; set; }
public string CompanyName{ get; set; }
}
public class Division
{
public int ID{ get; set; }
public string DivisionName{ get; set; }
public virtual Company Company { get; set; }
}
I have a strongly typed EDIT view for Division, with an EditorFor for DivisionName and a HiddenFor for ID.
The problem I have is when I hit save, the Controller action gets the Division object with an NULL for Company property. When the model is not valid, and the View is returned with that object, I can no longer extract the company name in the view using #Model.Company.CompanyName.
How can I fix this?
If you don't include Company data in your view (as input fields), then nothing about Company will be posted back.
If Company is just for "display only", then re-populate it in your controller during the post before your model is returned in the view.
public ActionResult MyAction(Division model)
{
// ...
// Repopulate Company
model.Company = new Company() { ... };
return View(model);
}