How to FluentBootstrap validation in MVC - asp.net-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

Related

How to hide primary key input field using editorfor

Hi I'm using Editorfor() to make a little form that submits view model to the controller. Editorfor() nicely prints input fields of the model but it also prints primary key field. So I want to hide primary key field.
#Html.EditorFor(m=>m.viewmodel)
this is markup that I have.
#Html.HiddenFor(m => m.viewmodel.Id);
#Html.EditorFor(m=>m.viewmodel)
have tried this but does not work. and I wanted to make an approach directly to the model but I'm using EF Designer, so I'm not sure where to begin. Please give me an advice.
Try this:
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set;
Use a custom editor template. For example:
MyViewModel.cshtml (stored in ~/Views/Shared/EditorTemplates folder, structured like a partial view):
#model MyViewModel
#Html.HiddenFor(m => m.Id)
#Html.EditorFor(m => m.Property1)
#Html.TextboxFor(m => m.Property2)
#Html.TextAreaFor(m => m.Property3)
// Whatever else you want in the template
Then you can just call EditorFor on your model in your view that needs to use it and MVC will know to use your custom template:
#Html.EditorFor(m => m.MyViewModel)
To use a custom display template that isn't based on the name of the type, you can also use the [UIHint] attribute as described here: http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html
Don't create any field for your key attribute. Without a field to check, the validation has nothing to complain about. Later you can supply a value for the primary key in the controller.

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.

How do I set up a check box with ASP MVC in my view?

I have the following class:
public class City {
public string Name { get; set; }
public bool CityValid { get; set; }
}
I know how to set up the name but how can I set up the CityValid field so it acts like a checkbox. I'd like to do this without using HTML helpers.
If you really don't want to use helpers, you would use a normal HTML input tag:
<input type="checkbox" id="CityValid" name="CityValid" value="#Model.CityValid" />
<input type="hidden" id="CityValue_Hidden" name="CityValid" value="false" />
The name attribute has to match your property name so that the model binder will pick it up correctly when you post back to the server.
When you use the helpers, something similar to the above markup will be generated. The hidden field is there so that a value is always sent with the form post data, regardless of whether you check the box or not (if you leave the box unchecked, no value gets sent by default, not even a 'false').
However, unless you're doing something really weird, I'd recommend you stick to using the helpers. Either:
#Html.CheckboxFor(m => m.CityValid)
or
#Html.EditorFor(m => m.CityValid)
In your view you could use the EditorFor helper:
#model City
...
#Html.EditorFor(x => x.CityValid)
The default editor template for a boolean field generates a checkbox.
You could first create it with a HTML-helper, look at the markup that gets created when running the page, and then recreate that markup...

#Html.EditorFor How to make attribute type="email"

I can do this easily using a TextBoxFor but how do I do it with an EditorFor?
I figured using the DataAnnotation [DataType(DataType.EmailAddress)] but that doesn't do it.
I don't quite understand what the DataType annotation actually does because it doesn't seem to do anything at all at first glance.
You can override the HTML Attributes, to which a browser will fallback to type='text' if they do not support it:
#Html.TextBoxFor(m => m.Email, new { #type = "email" })
it seems to be supported now.
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #type = "email" } })
The EditorFor helper method is somewhat limited out of the box and doesn't yet appear to support the HTML5 type="email" attribute.
Your options right now seem to be either using TextBoxFor or creating a custom template that will allow you to set the input's type attribute. Here's another thread that reviews some of the options for creating your own templates.
The DataAnnotation [DataType(DataType.EmailAddress)] is actually quite useful. It sets the id and name of your form field to email, which you can use with jQuery validation to show the user client-side validation messages. Applying the DataAnnotation to your model class also means that the email property on your model will be automatically validated on the server side. If you enable unobtrusive validation in your app, you get client- and servers-side validation almost for free.
As an addition to jortizromo's answer, you have now at least two options:
Specifying #type in the htmlAttributes parameter for method EditorFor() as in
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #type = "email" } })
Using the EmailAddress annotation attribute from System.ComponentModel.DataAnnotations namespace in the model class definition for the corresponding Email property and a simple call to method EditorFor() (this provides HTML validation data tags which could be a good or bad idea depending on your task) as in
ViewModel
[EmailAddress]
public string Email { get; set; }
Razor View
#Html.EditorFor(model => model.Email)

Resources