I have inline editing grid which using foreign key column. In the foreignKey.cshtml i also add the option label ("Please select").
Views:
columns.ForeignKey(p => p.EmployeeID, (System.Collections.IEnumerable)ViewData["testStatus"], "EmployeeID", "EmployeeName");
Model:
[Required(ErrorMessage = "Required")]
[DisplayName("Employee ")]
[UIHint("GridForeignKey")]
public int EmployeeID { get; set; }
Shared/GridForeignKey.cshtml
#(
Html.Kendo().DropDownList()
.Name(ViewData.TemplateInfo.GetFullHtmlFieldName(""))
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
.OptionLabel("Select value")
)
My question is, how i can validate if the user choose "Please select" option and display required message. THank you
Thank you
Try adding the range attribute instead of required to the model. More than likely your first item is of "please select" is being given a value of 0 or "please select" so the required attribute won't do what you need since technically that input has a value.
[Range(1, int.MaxValue, ErrorMessage = "Please Select A Value")]
public int EmployeeID { get; set; }
Also try add a selected index to your drop down list assuming you don't already have a selected value.
#(
Html.Kendo().DropDownList()
.Name(ViewData.TemplateInfo.GetFullHtmlFieldName(""))
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
.OptionLabel("Select value")
.SelectedIndex(0)
)
Did you try to add the [Required] data annotation attribute to your Model property? If you have not, is there any difference?
Related
In an ASP.NET MVC3 app I have a model that represents a user address with the typical Name, StreetAddress 1 & 2, City, Region, PostalCode and Country properties. The model currently has DataAnnotation attributes that apply to US addresses. I now need to support international addresses that will have different validation and messages depending on the Country value that is included in the model. How do I define and override the existing US DataAnnotation attribute values when the country is something like India or Japan instead of US?
For example the existing PostalCode property is defined as this:
private string _postalCode;
[StringLength(10, ErrorMessage = "Zip Code maximum length 10 characters")]
[Display(Name = "Zip Code")]
[Required(ErrorMessage = "Zip Code is required")]
[RegularExpression(#"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid Zip Code")]
public string PostalCode
{
get { return _postalCode; }
set
{
if (_postalCode != value)
{
_postalCode = value;
}
}
}
I know if I had a specific India address model then the postal code would look something like this:
private string _postalCode;
[StringLength(6, ErrorMessage = "Postal Code maximum length 6 characters")]
[Display(Name = "Postal Code")]
[Required(ErrorMessage = "Postal Code is required")]
[RegularExpression(#"^([0-9]{6})$", ErrorMessage = "Invalid Postal Code")]
public string PostalCode
{
get { return _postalCode; }
set
{
if (_postalCode != value)
{
_postalCode = value;
}
}
}
How can I implement the proper client and server side validations using this model when a user selects a particular country?
I'm expecting to either do an ajax call to retrieve an updated partial view when the country is changed, or send enough data to the client so I can adjust the client side prompts and validation by modifying the appropriate attributes on the input elements and resetting validation, but how can I get the server side model to validate properly when issuing a Model.IsValid() call?
With complex validations, I find it easiest to imeplement IValidatableObject interface
IEnumerable<ValidationResult> Validate(
ValidationContext validationContext
)
Basically something like this
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
MyAddress model = validationContext.ObjectInstance as MyAddress;
if (model.Country == "India")
{
// validate as india
}
}
This seemlessly integrates with default validation system, so you won't need any additional configurations. But to note, this is only the server side validation.
I am developing an ASP.Net MVC 3 Web Application using Razor Views. Within the View I would like to ask the user a question which can only have a Yes/ No answer, therefore, I am planning on using two Radio Buttons.
I have a ViewModel which I pass to my View, and it looks like this
public class ViewModelFormImmigration
{
public int immigrationID { get; set; }
public int formID { get; set; }
[Required(ErrorMessage = "Please select Yes or No.")]
public bool euNational { get; set; }
}
In my View I then have the following lines of code to display the radio buttons for both the Yes and No options
#Html.RadioButtonFor(model => model.euNational, true) <text>Yes</text>
#Html.RadioButtonFor(model => model.euNational, false) <text>No</text>
My problem is that, when the User comes to this View for the first time, I would like neither the Yes or No option selected. At the moment, when I create an instance of my ViewModel (see above), the property euNational is defaulted to false and when the ViewModel is passed to my View, this means that the option No is automatically selected.
Is there anyway around this so that when the User see's the View for the first time, that no option is not selected by default?
Thanks for your help everyone.
Try changing:
[Required(ErrorMessage = "Please select Yes or No.")]
public bool euNational { get; set; }
To:
[Required(ErrorMessage = "Please select Yes or No.")]
public bool? euNational { get; set; }
This way, when you first load the view with no value set for euNational it will not set to neither true or false. As at the moment when it has no value set, it defaults to false
Hey friends I am using drop down list in my mvc 3 project. Here the user choose one of the options and save it. And when he/she revisit the page than i have to make the initially saved value as selected value. Actually i am doing this with custom html helper as per need. But i am getting problem on it. I am doing this as:
else if (question_type == 7)
{
EAI.DAL.EaiEntities entities = new DAL.EaiEntities();
QuestionnaireRepository repository = new QuestionnaireRepository(entities);
SelectList typesList = repository.PopDdlList(qid);
output.Append(helper.Label(questiontext));
if (answer == "")
{
output.Append(helper.DropDownList("ddl" + question_id, typesList, "-- select type----));
}
else
{
output.Append(helper.DropDownList("ddl" + question_id, typesList, answer));
}
return helper.Raw(output.ToString());
}
Actually above code renders the selected value from database but it actually replacing the "-- select type ---" . So, After saving once if i visit the same page and save the page than i can get empty value in Formcollection.
So, please suggest the appropriate way of doing this
I usually add a few properties in my model:
int SelectedCategory { get; set; }
IEnumerable<SelectListItem> Categories { get; private set; }
and then load the data in my model constructor:
ProductService productService = new ProductService();
this.Categories =
productService.GetCategories()
.Select(c => new SelectListItem() { Text = c.Name, Id = c.Id.ToString() });
this.Categories.InsertAt(0, new SelectListItem() { Text = "--- Please Select ---", value = "" });
then in my Razor markup do something like:
#Html.DropDownListFor(m => m.SelectedCategory, Model.Categories)
This should auto wire up in the standard MVC way. Hope this helps.
I'm experiencing very odd behavior in the way an ASP.NET MVC3 view model is emitted -- for one field, ModelMetadata is not propagated. I'm using the templated helpers after Brad Wilson, though updated for Razor. Here's my view model:
public class FamilyBaseViewModel : ViewModelBase
{
[Display(Order = 10)]
public string FamilyName { get; set; }
[Display(Order = 30)]
[StringLength(50, ErrorMessage = "Street name can only be 50 characters long.")]
public string Street { get; set; }
}
public class FamilyPrivateViewModel : FamilyBaseViewModel
{
[Display(Name = "Date Started", Order = 20)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
[DataType(DataType.Date)]
public DateTime? DateStarted { get; set; }
}
The object.cshtml template runs through the properties and uses Html.Display to show them:
// object.cshtml
<ol>
#foreach (var prop in
ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay
&& !ViewData.TemplateInfo.Visited(pm)
&& pm.ModelType != typeof(System.Data.EntityState)))
{
<li>
#Html.Display(prop.PropertyName)
</li>
}
</ol>
In the above scenario, all three fields have the right descriptors in the object.cshtml call (prop.DisplayName, prop.TemplateHint), but when the first property -- FamilyName -- is passed to String.cshtml, the ViewData.ModelMetadata is not populated at all. As a result, the template can't display a label (except "String"), nor assign the ID of the control, etc.
Street and DateStarted are emitted normally, with the ID and all. So I'm completely at a loss as to why the one property would fail to set the ViewData properties -- nor do I know how to step through past the Html.Display call to see what might be happening.
Any ideas for a next place to look?
So the problem was in the controller action, which for unrelated reasons used "FamilyName" for a ViewData value:
ViewBag.FamilyName = familyName;
And this caused all heck to break loose in the mapping of model fields with the same name -- that is, ModelMetadata will not propagate. So, the lesson is: don't give ViewData dictionary items keys with the same name as a field in your view model.
code is:
#using (Html.BeginForm("Register", "User", FormMethod.Post, new { id = "RegisterForm" }))
{
#Html.DropDownList("StateId", new SelectList(Model.States, "StateId", "StateName"),
"--Select an option--", new { #tabindex = "11" })
}
i need required field validation for dropdown
Have you tried using Data Annotations in your model to mark the property as required?
[Required(ErrorMessage = "You must select a State")]
Are you exposing the StateId as a part of the Model? If so that's where you should set the Required Attribute, like so:
[Required(ErrorMessage = "You must select a State")]
public int StateId { get; set; }