Modelstate.Isvalid showing false - asp.net-mvc

I have made a web application in MVC Razor. When I post/submit the page DATA ANNOTATION validation fires on those fields also which was hidden/or not shown to user. As dataannodation [Required] validation are put on hidden properties also, I am getting False value on ModelState.IsValid. And since the project is on the verge of completion we can not change or remake the MODEL Class.
Please somebody suggest me how to achieve this..If my question is not clear please let me know.

You can use
ModelState.Remove("FieldName");
to remove entries in model state, that are related to hidden fields.
Please at least make sure, that safety of the system is not compromised by using [Bind(Exclude = "Property names")] attribute to disable binding of fields, that should not be sent from form.

Related

MVC required fields on optional object

I have a complex view model which has some subclasses. For the sake of a simple example, let's assume there's one subclass.
That subclass is displayed by rendering a partial view. The user can toggle that view in the interface, completely hiding the whole thing.
Now there are two valid input options:
The user chooses to hide the partial and doesn't fill in anything. The whole thing should be ignored.
The user chooses to view the partial, now he has to fill it in. Some of the fields are required, some are not.
What's a good way to handle this is MVC validation? I cannot mark the fields as Required, since the postback will post the empty values and the server side logic will say ModelState.IsValid is false beacuse there are fields missing.
Of course I can lose the [Required] attributes and do the checks manually myself, but I was wondering if there's no better way to get the same result.
The simplest way of doing this is like this ASP.NET MVC 3 Data Annotation: Add validation dynamically.
For a harder (a bit nicer) solution read this: DataAnnotations "NotRequired" attribute

Two-Way-Binding Possible In ASP.NET MVC?

Let's say I have a product object (pretty much empty) and I bind it to a Product view. Then I click update in the view. In my CustomModelBinder my bindingContext.Model is always null on the update request. Is there a recommended way of me retrieving the prior model at this point or do I always have to recreate it?
You have to recreate it from the form fields. The values you bound to the model for the GET are long gone.
perhaps im not understanding your needs to use a CustomModelBinder, but did u concider Data Annotations Model Binder yet?
it even comes with (serverside) validation based on simple statements like [Required] which u can put right inside your model, see this

asp.net mvc how to save?

I have the following model:
Customer:
ID
Name
Address
Phone
Fax
I added an Edit view based on the above model from the controller. I modified the Edit view to only allow edit on the Phone and Fax field (deleted the rest). When I submit it I get an error. It works if I leave the Edit view untouched (5 fields). However I only want to allow change in the last 2 fields.
I am lost, please help. Thanks :)
If you are using the MVC ability to populate your entity/class i.e. your action sig looks like this:
ViewResult MyAction(MyObject object) {
...
Save(MyObject);
}
then you'll need to make sure you include the other field, non-editable, either as visible information or using Html.Hidden within the form scope to ensure you have a fully populated object. Remember, the web is stateless and the server has no idea which record you were editing unless it has the keys to do so retrospectively.
The other option would be to retrieve the original object (for which you'll still need the primary key) from the database, update the fields from your form data and then submit the changes. We'd need to know the specific error to be able to help further, the code you are using would also be a great help.
Without knowing more I would guess it has something to do with binding null to a non null property in your model. Can you give me more details on the model, the error.
If you are using the default mvc model binder then it will only bind the fields you submit. So either submit as hidden or dont use a model binder and manually map the variable from Request.Form into a copy of the model you pulled form the db.

Model not rendering model values after post

I have an ASP.NET MVC page that has a list of items...
//a vague representation
Model.someValue[0] Model.someHiddenValue[0]
Model.someValue[1] Model.someHiddenValue[1]
Model.someValue[2] Model.someHiddenValue[2]
All fields are optional, but they do have some validation, of which I am showing validation messages.
The problem is, when I submit once and return the original view instead of a redirect, the hidden fields are not getting their new value, but their new value is in the view model being passed to the view.
I am thinking the ModelState might be overriding the model as part of validation. I know I can do a redirect and bypass the problem, but I want be able to save part of the form and show validation errors for the rest. If there are no other solutions, I will simply validate the whole form and only save when all items are valid.
If values are present in ModelState, it shows them instead of the values in your model, since they represent the "last" known state provided from the user.
You should clear out ModelState if you're not actually intending the user to re-do their edits.
Did you try this?:
var newValue = new ValueProviderResult("value", "value", System.Globalization.CultureInfo.CurrentUICulture);
ModelState.SetModelValue("someHiddenValue", newValue);

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