how to validate Viewmodel in multiLang in mvc - asp.net-mvc

I have this viewModel and I use Asp.net MVC and EF code First .
public class AddNewsVM
{
public string Title { get; set; }
public string TitleEn { get; set; }
public string Body { get; set; }
public string BodyEn { get; set; }
public string Author { get; set; }
public bool IsActive { get; set; }
public Guid ImageId { get; set; }
}
But user can Add EnNews(englisg) Or FaNews(persian) or both of them . I don't Add Required to all them . how can I validatie it . for example I want if use enter En News Title user should enter All En Field . do I use If statement in Action ?

It depends on your needs. If you need both (client / server) validations, I recommend to use:
https://github.com/JeremySkinner/FluentValidation
If you want to just validate your ViewModel on server side (class level validation), you can write your own custom validation rules using the IValidatable.
http://weblogs.asp.net/scottgu/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3

You can do client side validation like this
create one javascript validation metod.
perform all your custom validation, if validation fails return false at the end return true.
call the validation method on submit button "onclick" event
eg:- onclick="return myValidationFunction()"

Related

MVC.net Hiding Fields within a model

So I am creating a an API with ASP.net MVC Web API. I currently have a model which contains the fields for a user in the database. I have a password field on this model. See below for an example.
public class Account
{
[Key]
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
I return this model using JSON when a controller method is called over HTTP. This works fine.
My question is, how do I stop the password field being returned alongside with it? Without removing the field altogether.
My initial idea is to create another model class which I use to return the data without the password field, but I'd rather not repeat myself for the sake of one field.
Any suggestions?
You should be able to mark these fields with
[JsonIgnore]
[XmlIgnore]
public string Password { get; set; }
Preventing these fields to be used in either JSON or XML requests.

ASP.NET MVC - ViewModel validation best practices

Let's say I got the following Entity Framework "Ruimte" model:
public class Ruimte
{
#region Constructor
public Ruimte()
{
Kenmerken = new List<Kenmerk>();
}
#endregion
#region Properties
[Key]
public int Id
{
get;
set;
}
[Required]
public string Naam
{
get;
set;
}
public List<Kenmerk> Kenmerken
{
get;
set;
}
#endregion
}
And the "Kenmerk" model looks the following:
public class Kenmerk
{
#region Properties
[Key]
public int Id { get; set; }
public KenmerkOptie KenmerkOptie
{
get;
set;
}
[Required]
public int KenmerkOptieId
{
get;
set;
}
[Required]
public string Waarde
{
get;
set;
}
[Required]
public int RuimteId
{
get;
set;
}
#endregion
}
And in my Ruimte/Create view there are 2 fields for adding a "Kenmerk". Now a "Kenmerk" can't go into the database without having a KenmerkOptieId or Waarde. So the view will reject the submit everytime I try to post the form because of the validation. Though I want a "Ruimte" to have or not to have a "Kenmerk".
So the solution I went for was having a "RuimteCreateViewModel" with the properties "Name" which was required and a list of the another copmlex class called "KenmerkCreateViewModel". Now in this last viewmodel the KenmerkOptieId and the Waarde are not required so I finally CAN submit the form.
Though I don't think this is the best solution of "skipping" the required field validators. So what is your "best practice" when the database validation is different from the view validation?
I think xVal - a validation framework for ASP.NET MVC, see http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/ is very useful for the entity framework model that you are trying to develop. Especially the use of enforcing server-side validation, it allows you to choose to validate simple property formatting rules during property setters. See http://blog.stevensanderson.com/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/ for an explanation.

Filter some property value in post data by ASP.NET MVC 3

I have a model like the followings:
public class MyModel {
[Required]
public string Name { get; set; }
public string Family { get; set; }
[Required]
public int Number { get; set; }
}
So for example in Edit View I have 3 Editorfor() objects and I am interesting to filter the post data of this page, actually I want to ignore Number field and just want to post Name and Family Also I need the validations of Number be active, One way is I remove Number property from MyModel and define in view by hand and write all validation script by own, but I am interesting to know is there any simpler way in MVC. Does anyone have any idea?
Controlling all that validation and model binding manually is way too complicated and error-prone. You should be using ViewModels
public class SomeSpecificViewModel
{
[Required]
public string Name { get; set; }
public string Family { get; set; }
}
public ActionResult SomeSpecificAction(SomeSpecificViewModel model)
{
//...
}
Now MVC wil validate only Name and Family
Any value not filled in the view will not be posted to the controller. However, if a field which is [Required] is not filled, then ViewModel.isValid will be false.

asp.net mvc 3 rc1. ModelBinder populates all properties with null

I have an object like this
public class ParentEntityInfo
{
public long? ParentId { get; set; }
public string EntityName { get; set; }
public string ParentProperty { get; set; }
}
and view for this object is:
<%=Html.Hidden("parentInfo.ParentId", parentInfo.ParentId)%>
<%=Html.Hidden("parentInfo.ParentProperty", parentInfo.ParentProperty)%>
<%=Html.Hidden("parentInfo.EntityName", parentInfo.EntityName)%>
I have the case where parentInfo is null and I post this form to controller. On the controller action
public ActionResult SomeAction(..., ParentEntityInfo parentInfo)
I receive constructed object parentInfo but all properties are null. In this case I would rather prefer to have whole parentInfo to be null. I there any possibility to tell default model binder do not pass such object? Or probably I can modify something in this code to make it work this way. I think in mvc 2.0 it worked this way.
Use the HiddenFor(...) helper instead.
I think the default model binder will always use Activator.CreateInstance to bind complex action parameters. What you can do is use ModelState.IsValid to assess whether the parameter was bound successfully. I think in your case this will be false by default, but if not you could add the necessary attribute to ensure this behaviour e.g.
public class ParentEntityInfo
{
[Required(ErrorMessage = "Parent required")]
public long? ParentId { get; set; }
public string EntityName { get; set; }
public string ParentProperty { get; set; }
}

asp.net mvc DataAnnotation Validation

i going to create some validation for custom object in my app. But i have some trouble when try to create CustomValidation rule. My object has field - BirthDay - which not required but if user enter it i need to validate it on simple validation, for example user DataType validation - DataType.DateTime. When i am try to do it i have validation error - BirthDay is required. When i create custom validation and always return true i have same error. Below some lines of code:
[MetadataType(typeof(User.Metadata))]
public class User
{
#region Metadata
private class Metadata
{
[Required(ErrorMessage="Name is required")]
[StringLength(5, ErrorMessage="Max Length is 5")]
public string Name { get; set; }
[CustomValidation(typeof(User), "ValidateBirthDay", ErrorMessage="We have trouble.")]
public DateTime BirthDay { get; set; }
}
#endregion
public static bool ValidateBirthDay(object value)
{
return true;
}
public int? ID { get; set; }
public string Name { get; set; }
public DateTime BirthDay { get; set; }
}
p.s. sorry for my English =)
You need to make your propery nullable, ie
public DateTime? BirthDay { get; set; }
so it can have a null value and not required to be set.
Also the way you use the CustomValidation attribute doesn't seem right. I believe you need to create a class that derives from ValidationAttribute base class and pass its type in CustomValidation attribute's first param.

Resources