Required Validation Message MVC - asp.net-mvc

I need to add a validation control in ASP MVC for a textbox. I used the #Html.ValidationMessage helper.
There is one textbox and I want to show the error If the value is not entered in that field.
I used the following code.
#Html.TextBox("txtStudentNumber", "4234234");
#Html.ValidationMessage("txtStudentNumber", "Please enter the student number", new { #class = "text-danger" })
The above message is always shown irrespective if the textbox has a value or not.
I need to validate if the student textbox is empty and also when the save button is clicked.

First of all, you have to use strongly types controls. i.e you should use TextBoxFor instead of TextBox and use ValidationMessageFor instead of ValidationMessage.
and then you have to bind the textbox with model. Try this :
Step 1: Create one model class "ClsStudent"
public class ClsStudent{public int studentNo {get;set;}}
Step 2: Bind the model student number in the view :
#model ClsStudent
#Html.TextBoxFor(m => m.studentNo)
#Html.ValidationMessageFor(m => m.studentNo, null, new { #class = "error" })
Validation on Submit Button :
Submit

Related

How to save the user email address into 2 different textboxes

Basically I have 2 textboxes; I would like whatever the user types into the email textbox to be saved into the name textbox as well.
Basically saving the email address in 2 places. I’m new to MVC any examples would be good, cheers.
#Html.TextBoxFor(m => registerModel.Name, new { #class = "form-control" })
#Html.TextBoxFor(m => registerModel.Email, new { #class = "form-control" })
If you want to save the same values for the both text fields, you can assign same value to both on post function, there is no need for an additional text field.
But if you want to display same value for both text box while typing on one text box. Then try following javascript.
$("#Name").keyup(function(){
var Names = $("#Name").val();
$("#Email").val(Names);
})

How to FluentBootstrap validation in MVC

Is it possible to use validation messages in FluentBootstrap on form element level?
When I use:
#using (var form = Html.Bootstrap().Form().Begin())
{
#form.InputFor(m => m.Name)
#form.Submit()
}
There is no validation, except validation error class on input tag. I want to show validation message for Name property and has-error class on form-group container.
Just add #form.ValidationSummary() where you want the general validation summary to appear. There is an example of this as well as some other examples here: https://github.com/daveaglick/FluentBootstrap/blob/develop/FluentBootstrap.Tests.Web/Views/MvcTests/MvcForms.cshtml
If there is no particular reason to use InpuFor you can do the following.
#form.EditorFor(m => m.Name, addValidationMessage: true)
This will show what error message you put on your Name property's attribute.
Such as
[StringLength(50, ErrorMessage="Cannot be longer than 50 character.")]
public string Name { get; set; }
I personally use the base validation helper
#form.InputFor(m => m.Password, FormInputType.Password)
#Html.ValidationMessageFor(m => m.Password)
I can set the type of the input unlike the case when I use EditorFor

Mvc 4 validation summary errors not displaying

I am having trouble displaying validation summary, I only want to display errors in validation summary, not beside the field.
In my view i have,
#Html.ValidationSummary()
#Html.ValidationMessageFor(m =>m.Name)
in my controller i have
ModelState.AddModelError("Name",
"name is required");
Am i not supposed to get a validation error message? at the top?
I don't get what i am missing...
I am also including these script files..
jquery.validate.min.js
jquery.validate.unobtrusive.min.js
Try
#Html.ValidationSummary(false)
so that it will not exclude property errors.
OR
Try the method #xurca linked which is to add the model error with an empty key so it is not tied to a specific property.
ModelState.AddModelError(String.Empty, "name is required");
If you custom named your field like
#Html.TextBoxFor(model => model.Name, new { id = "staffSearchFilterName", value = "", **Name = "staffSearchFilterName"** })
then you have to use
#Html.ValidationMessage("staffSearchFilterName")
If your #Html.ValidationSummary() call is in a Partial view, DON'T pass data into the partial view like this:
#Html.Partial("_YourForm", Model, new ViewDataDictionary { { "Submit", true }})
Instead, add the key value pair to Html.ViewData collection first:
#{
Html.ViewData.Add(new KeyValuePair<string,object>("Submit",true));
}
then call the partial view:
#Html.Partial("_YourForm", Model, Html.ViewData)
this will allow the ModelState to propagate to the partial view properly.

DropDownListFor enum doesn't bind back to the model

On my MVC form, I need to bind a drop down box to an enumeration on my ViewModel. The best way I found to do that is described here.
It appeared to work at first, but now that I've added validation to my form, I've discovered it does not bind back to the ViewModel.
Here's my razor code:
<div class="editor-field">
#Html.DropDownListFor(model => model.response,
new SelectList(Enum.GetValues(typeof(Vouchers.Models.ResponseType))),
"Please Select")
</div>
And here's my view model definition for the field:
[DisplayName("Response")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a response before submitting this form.")]
public ResponseType response { get; set; }
The problem is that I cannot submit the form; even after selecting a response from my drop down, the Validation error message for the Range attribute is displayed and the client side validation prevents the form from submitting.
I believe this is because the SelectList for the drop down contains only the string names of the enum, not the underlying integer value.
How can I solve this problem?
Create Dictionary where Key will be integer representation of the enum and string- the name of enum.
#Html.DropDownListFor(model => model.response,
new SelectList(Enum.GetValues(typeof(Vouchers.Models.ResponseType)).OfType<Vouchers.Models.VoucherResponseType>().ToDictionary(x => Convert.ToInt32(x), y => y.ToString()), "Key", "Value"), "Please Select")
Sorry for possible errors, I have not tried it.

Why does my MVC dropdownlist have a value selected despite the property value being NULL?

I have a dropdownlist where a user can select a care provider. In the database the value for this is null however in the application, a value is selected. What do I need to do to have the null value appear as a blank? I thought this was the default behavior. I changed to using strongly typed lists in my view model instead of the viewbag and this may have broken at that time.
Here is the view markup:
<div class="editor-label">
#Html.LabelFor(model => model.PsychologistId, "Psychologist")
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.PsychologistId, Model.ListPsychologists)
#Html.ValidationMessageFor(model => model.PsychologistId)
</div>
Here is the property from the view model:
[DisplayName("Psychologist")]
public Nullable<int> PsychologistId { get; set; }
Here is the relevant part of my controller:
model.ListPsychologists = new SelectList(XXX, "Id", "DisplayName");
return this.View(model);
where XXX is just the LINQ expression with filtering and sorting criteria. It's been omitted for clarity and space.
The model passed from the controller to the view has PsychologistId being null. And the SelectedValue property on model.ListPsychologists is null.
if PsychologistId is an int, it will assign 0 value to it since int is not a nullable type.
Show your model and controller if my assumption above is not true.
Does your SelectList contain entry with Id==null? I doubt that. And that means that you will have no select list entry matching your value, so browser will select first one available.
Solution: explicitly add entry with Id = null to your SelectList.
I've had these issues before, and what I did to fix it was send the base collection of what I want to fill the dropdown with in the viewmodel, instead of a SelectList. So:
model.ListPsychologists = XXX;
Then in the view:
#Html.DropDownListFor(x => x.PsychologistId, new SelectList(Model.ListPsychologists, "Id", "DisplayName", Model.PsychologistId))
Please verify the SelectList constructor overload I used in MSDN, I'm typing this from memory. Basically you give it the collection of items to use in the SelectList, then the name of the text and value properties (just like you did in your action method code), and the fourth parameter is the value to set the drop down to.
Edit: Also, there is an overload for the DropDownListFor to add a default item in the menu. Like, "Select One".

Resources