MVC Controller Error Messages - asp.net-mvc

In MVC 3 app I have a few conditional elements in the controller. for example I have a number say "10" which has met the model state requirements but I have a if statement that checks if the number "10" exists in another table. Should it exist the data is submited but should it not exist I return the view and would like to return a error message.
My question is what would be the best way of displaying a error in this situation. I have looked at returning a viewbag message but I would like to style the error message with a box and by adding this style to the view it always gets displayed which is a problem.

You could add the error message to the modelstate:
ModelState.AddModelError("somekey", "some error message");
and inside your view display error messages using the validation summary helper:
#Html.ValidationSummary(false)
You could of course add a string property to your view model and set its value in case of error. Then inside the view check whether the model property has a value and if it does display the error messages inside a custom styled element. It seems a bit like a wheel reinvention assuming you could simply append the error message to the modelstate but worth mentioning.

Related

MVC Show different ValidationSummary ErrorMessage compared to ValidationMessage

In ASP.NET MVC, is it possible to show a different message in the ValidationSummary compared to what is shown in the ValidationMessage?
IE - if i have a FirstName textbox, on validation the message next to the text box will say 'You need to fill this out', but in the validation summary it will say 'Please provide a first name'.
I'm not sure if I completely understand what you are trying to accomplish, but you can specify a generic error message in the validation summary. In your view you can use:
#Html.ValidationSummary(true, "Please correct the errors below")
The boolean parameter indicates whether you want to exclude property errors. The string is the message you want displayed. Using this overload the way I have above, the model-level error message Please correct the errors below would be shown in place of the #Html.ValidationSummary() method, and the property errors would be shown where you place your #Html.ValidationMessageFor() methods.
See the MSDN documentation for a complete list of overloads.
Yes. It should be quite obvious from looking at the intellisense.
you would say:
#Html.ValidationSummary(true)
and it will contain the error messages that are located on the model or the default messages
And you can say:
#Html.ValidationMessageFor(m => m.Property, "This is a custom message")
And that overrides the message on the individual message.
Also, keep in mind that #Html.ValidationSummary(true, 'Header Message') will show your custom summary message along with the same messages that you provided in your model data annotations.
i.e. in your model class:
[Required(Message="First name is required")]
public string FirstName { get; set; }
Your validation summary would look some like this:
Header Message
First name is required
Alternatively, you can build up a custom collection of messages by using ModelState.AddModelError("Key", "Message") in your controller, then referencing that key in your view using ViewData.
After looking at the Metadata available, I don't think what I want to do is possible. What I'm going to do instead is type in the input specific value for validation, and hide the class field-validation-valid.
Providing different Errormesages beside the input fields and in the Validation Summary is not possible with #Html.ValidationSummary. Such a feature could make sense because a part of the errormessage's information can come from it's position in the page (e.g. beside a firstname input field the message could be 'Input required' and in the validation summary you need 'Input required for firstname'). Unfortunately a poor implementation for ValidationSummary in MVC, .net 2.0 provided the feature to have different messages in it's validators and in the validationsummary .

How to get ModelState Errors at runtime using Key added by ModeState.AddModelError( key,value)

I have added Model error from controller using
if( model property not selected)
{
ModelState.AddModelError("SelectionRequired","Please select atleast one value");
}
This error I am adding at many places in that same method but ultimately I want to show to user only one such message out of the ModelState errors collection.
For that purpose before returning to view I have to remove all similar messages except one.
How can i remove this messages using "SelectionRequired" i.e. key and not using "Please select atleast one value".This "SelectionRequired" is not a model property name is just a key we want to use.
I checked ModelState.Keys collection at runtime I don't see the "SelectionRequired" at all in those collection and also not even in ModelState.Values collection. Then where does this key *"SelectionRequired" goes ? and how to select errors based on it ?
is there any better way to do this ?
This might work:
var error = ModelState["SelectionRequired"].Errors.First();
ModelState["SelectionRequired"].Errors.Clear();
ModelState["SelectionRequired"].Errors.Add(error);

Changing text if a form has an error

I currently have a summary message at the top of my form, inviting my user to login. If the form does not validate on submit, I wish for this to then be replaced with the relevant error.
The only way I can think of is by hiding the initial text (perhaps in a #Html.Label) and then showing a #Html.ValidationSummary. However, I feel there is most likely a far more efficient way of doing this.
Can anybody help?
I would have an #Html.Label helper, and use the ViewBag object to pass data to it. That way in your controller when you test for ModelState.IsValid, if that is false you can set the ViewBag property so that it passes to the label helper.
Make sense? That's how I'd do it.
turn on the validation summary
#Html.ValidationSummary(true)
in your post ActionResult check the ModelState
[HttpPost]
public ActionResult Foo( Bar _bar){
if(ModelState.IsValid){
//noral course of action
return RedirectToAction("Foo"); //Redirect to the GET method
}
ModelState.AddModelError("", "|Your Message Here");
return View(_bar);
}
No, there is no problem with the approach.
I generally use single div with jquery for the stuff like form validation etc.
I create a single div on page where any kind of message can be displayed for user guideance.
ex:
if I've display some kind of information to user, it will be displayed as following:
div id='divMessage'</div>
$('#divMessage').html('Please fill the following form.').removeClass().addClass('msg');
While in case of some error same div will be used to display the error message:
$('#divMessage').html('some error occurred.').removeClass().addClass('errmsg');
I hope till will be of any use.

MVC3 Validation Issue NullReference Exception

When I click the submit button on my form, I get a null reference exception error during the reload following the submit event, that is generated by my dropdownlist.
The data loads fine during initial load. It is my understanding that the data is maintained by convention and should be retained.
I also looked at the modelstate and the error for the required field was raised and the error message exists inside the ModelState object.
But, it looks like this convention is not working for this dropdown. So, this line below raises the error:
#Html.DropDownListFor(m => m.Company.DeptId, Model.DeptList)
What am I doing wrong?
The value for the posted model property (DeptId) is retained, but the contents of the property DeptList are not since they were not posted back. Only the properties on the model that correspond to form elements that are posted can be reconstituted on the model. On error you'll need to repopulate any properties of the model that don't correspond to inputs in the view so that the view renders properly.

MVC - How to change the value of a textbox in a post?

After a user clicks the submit button of my page, there is a textbox that is validated, and if it's invalid, I show an error message using the ModelState.AddModelError method. And I need to replace the value of this textbox and show the page with the error messages back to the user.
The problem is that I can't change the value of the textbox, I'm trying to do ViewData["textbox"] = "new value"; but it is ignored...
How can I do this?
thanks
You can use ModelState.Remove(nameOfProperty) like:
ModelState.Remove("CustomerId");
model.CustomerId = 123;
return View(model);
This will work.
I didn't know the answer as well, checked around the ModelState object and found:
ModelState.SetModelValue()
My model has a Name property which I check, if it is invalid this happens:
ModelState.AddModelError("Name", "Name is required.");
ModelState.SetModelValue("Name", new ValueProviderResult("Some string",string.Empty,new CultureInfo("en-US")));
This worked for me.
I have a situation where I want to persist a hidden value between POST's to the controller. The hidden value is modified as other values are changed. I couldn't get the hidden element to update without updating the value manually in ModelState.
I didn't like this approach as it felt odd to not be using a strongly typed reference to Model value.
I found that calling ModelState.Clear directly before returning the View result worked for me. It seemed to then pick the value up from the Model rather than the values that were submitted in the previous POST.
I think there will likely be a problem with this approach for situations when using Errors within the ModelState, but my scenario does not use Model Errors.

Resources