ASP.NET MVC Using view models in different views - asp.net-mvc

I have 2 customer views one for create and one for edit. I am using the same customer view model for both. I want to make the 'customer no field' required on the add, but not the edit.
If I put the requiredfield attribute on the view model property then both views flag 'Customer No' as required (as you would expect).
Is there a built in solution to get around this problem or Am I going to have to create 2 seperate view models, one with the attribute and one without.
Thanks

This is similar to this question.
I would strongly advise you to tailor 2 View Models for edit and create actions. It is a lot cleaner. The last answer in the link I gave you makes a workaround and disables the errors on the ModelState.

How is Customer No. required on create but not edit?
If you create it, it requires the number, and when you edit it, the number is still there.
Do you mean they can remove the customer number on edit? Or do you mean you want Customer no. to be non-editable on edit?
If it's the latter, then you can keep customer no as required, you just display the customer no in your edit view (not in a textbox) and use a hidden input to contain the number so it gets posted.

Just a concept type of suggestion. Remove the required validation attribute from your model. In your controller, make the parameter optional and depending on which Action (Edit or Create), you'll manually add in some type of validation.
The jQuery validation can be used to validate from the client based on the input if you go towards the manual route.

Related

How to use same scripts in views

I have a view for creating an entity by filling a form. That form contains several inputs and 2 datatables table. i write a considerable amount of JavaScript code for initialization and validation of the inputs. For editing the entity, i need the 95% of inputs and JavaScript codes.
First, I tried to move the common codes to a partial view but some of them worked and some of it didn't work. For example the tables not initialized.
As a second approach, I can also write a lot of if-else to check the current page (between Create and Edit) and do proper action.
How can i have two views and common codes in both? Is there a better or functional approach?
save your javascript code as js file. Drag and drop its link where you want to use it :)
You can use the same view for Create and edit functionality.
And regarding the inputs, you can take one property in the model which will indicate whether to show or not to show that input on UI.
Model:
For eg. Public string displayInput=[none/block]
view:
You need to set the value of displayInput field properly when you want to show all fields and when you want to hide some fields.

MVC4 - getting list of fields in View

Is it possible to safely programmatically get a list of fields that are in the View that has just posted back to a Controller?
I noticed a problem with the default implementation of the scaffolding, in
DB.Entry(model).State = EntityState.Modified
DB.SaveChanges()
The problem is that if I haven't included a field to be edited in the view, it is being overwritten by the default value of the field that .NET assigns when creating the object. eg. If I have a User class with ID, Email and PasswordHash and I want to allow the user to update their Email address only, if I don't include anything for the PasswordHash field, it is reset to NULL as it is passed into the controller as NULL. At the moment, I am working around it by retrieving the current object from the database and updating only the fields which I know are in the View from the model passed in. That isn't such a problem for a small table, but I would like to have a general solution that I can apply across the board, especially for large tables which may during development and I don't want to have to update the code every time.
I know that I could loop through the POST variables and examine them to see what has been posted, but that creates a security issue as the user could inject additional fields that I don't want them to edit. I suppose I could explicitly exclude ones that I don't want them to edit, but then again, I would rather not have to list those if I can avoid it as it is an extra thing to maintain.
I think that there are 2 problems here and I'm not sure either are solvable...
Getting the View that posted back
Establishing which fields are included in that View (I might need to construct it again temporarily to do that?)
I suppose that I can probably get away with ignoring the first one as I could just only ever use that method on the Controller for a single View. That is still a little less neat than I'd like, but it does reduce the issue to just establishing which fields are in the View.
If a view needs only certain properties, create an interface with only those properties. Use this interface in the HttpGet and HttpPost methods.
And then you can use something like AutoMapper to map the viewmodel to your entity.

MVC Razor How to get the model in the Controller on HttpPost when the model is dynamic

I'm working a feature in the application where model will be dynamic in the sense that any settings data could be displayed and the view will get the model based on what tab they clicked on. I use Hidden field to store what the settings name was because they are same as model name. for ex., if tab1-> Settings1 then Model is Settings1[already exists in the Model].So I used # model dynamic in View and used #Html.EditotForModel() to draw the required UI based off the model. My problem is when I do HttpPost on Edit currently I'm using FormCollection to read the data on that page when I declare the model name in the param it will get it for me but I don't know which model is coming back other than by the Hidden variable and I need it because the Model validation is broken because of this issue. Any help or feedback is appreciated? I can give more details if required? Has anybody crossed this issue before??
Dynamics can be a good thing and a bad thing. Using them on models that have a common interface in a controlled manor is best.
There are different options that you can look at:
1)
Have you tried making the action method accept a dynamic type? That might be the easiest way.
You might have to set up a casting helper to cast the object to the correct type based on the hidden field.
2)
I have a similar idea in some code, but I created a viewmetamodel class that contained all my types as nullable properties. My action method accepts this viewmetamodel type and validates the properties that are not null.
In line with this, if your data is not too large, then you could load all the settings tabs and use Jquery apply the tab with on click.
3)
You could also create #sections or use EditorFor(c=>c.settings) for each tab. That way each tab will load a type safe object. You would need to create controllers for each.
I would say pick the easiest method for you. I hope that this at least gives you some ideas.

Should I render optional sections of a form via partials?

As an exercise in learning .NET, I'm moving some simple forms over into MVC, and have run into an issue. The form in question is a multi-part form that has option sections. For example, Section 0 is static and contains information like username, real name, email address. After that is a radio button with several options. If you click the first radio, it displays Section 1. If you choose the second, it displays Section 2, and so on.
In WebForms this was no biggy, as I just validated on postback and said if Radio1.Selected validate this, if Radio2.Selected validate that, etc. So now I've got a strongly-typed view with [Required] members, which obviously isn't going to work - I can't require members that aren't always going to be required.
With that said, is this the correct approach to the problem:
Create the members that belong in Section 0 in my strongly-typed view model class.
Create references to each partial's strongly-typed class in my view model class.
Create the partial views and then render them in the main view.
Depending on which radio button is selected, render the appropriate partial view.
Validate the model like usual...which hopefully will cascade to the partial models.
Does this make sense, or is the approach wrong?
That's a typical scenario where you need conditional validation, i.e. if some value is set then validate that some other value is required. Achieving this with static data annotations which are simple attributes baked at compile time can quickly turn into a nightmare due to their declarative nature. Well, you could always roll your own custom validation attributes but the problem with attributes is that you will have to specify property names as strings as they need to be known at compile time.
That's one of the reasons why I use FluentValidation.NET. Not only that validation rules are separate from the view models and that it integrates really nicely with ASP.NET MVC but handling scenarios like this would be very easy. You could have a sub-view model containing all the properties of the sub-section and then conditionally include it based on the value of a given property on the main view model inside its validator.

Make all form fields readonly in MVC

I am displaying 3 or more versions of a form. One version is an edit form to edit all fields. A second version will be a read only version of the same form which will be used to show all the same fields but with all fields having readonly="true" on the client side so that the user cannot enter data. The readonly fields need to use a different css style. This is to display archived data. I am already hiding the submit button so they can't submit but I want the form to look like it is readonly. A third version will have some fields readonly and some editable for a particular class of users that has limited editing privileges.
I am using ASP.NET MVC 1.0. How do I modify all (or a subset) of the fields displayed so they are readonly. I would like to iterate through the collection of fields in the controller and set them all to readonly and also set the correct css class. I don't want to have to put an if statement on every field in the .aspx file (there are 40-50 fields) and I'd prefer not to have this on client side so I can prevent users from modifying javascript/html to edit things they are not supposed to.
TIA,
Steve Shier
Keep in mind that even if you set the tags as readonly on the server side, users can still change them through a variety of means, and whatever the value on the form is before it gets sent back to you.
Certainly the easiest way is client-side with jQuery:
$(function() {
$('input, select, textarea').attr('disabled', 'disabled');
});
Or, you could do it in your View, but it's ugly. Off the top of my head, you would need some sort of bool passed into the View (via ViewData I suppose), and check that on each Input to see if you should add the disabled attribute. Not my idea of fun...
I would have different views that correspond to your states and then choose the view depending on which state you are in. You could also implement it with partials, breaking down the pieces so that you can easily include editable or read-only versions of the different sets of elements. The read-only view, then, need not even include a form element. You could also present the data in spans, divs, or paragraphs rather than as input elements.
Note: you'll still have to check whether the current user has the ability to update/create data in the actions that process form submits. Just because you limit the ability to view data in a read-only format, that won't stop someone from crafting a form post to mimic your application if they want. You can't rely on hiding/disabling things on the client to prevent a malicious user from trying to enter/modify data.
I usually use partial views to represent forms and/or parts of forms.
I can think of two simple ways to do what you need (as I understood it):
<% Html.RenderPartial(the_right_partial, model); %> where the_right_partial is either a value passed from the controller or a helper (in which case, the_right_partial(something));
pass a bool or enum paramether from controller representing editability and then using a helper to obtain the right htmlAttributes, like:
<%= Html.TextBox("name", value, Html.TheRightHtmlAttributesFor(isReadableOrNot)) %>;
There may be other ways, like creating new helpers for input fields which accept an additional isReadableOrNot arg (but it seems an overkill to me), or like mangling the html/aspx in some odd (and totally unreadable/unmaintainable way), but I'd not suggest them.
Notice that using html attributes like disabled is client side, and with tools like firebug it takes just two seconds to change them.
Others have already said it, but I also have to: always assume that the user will do his/her best effort to do the worst possible thing, so check the user rights to modify stuff on server side, and consider client side checks as a courtesy to the user (to let her/him understand that the form is not supposed to be edited, in this case).
Since I am trying to use a single partial for the different states of the form, I am thinking I will create helper functions which will display correctly based on the state and the user. The helpers will use a dictionary of fields that will indicate under which condition the field is read only. I will still have server side checks to make sure data is valid and the user is authorized to make changes.
Thanks for all of your ideas and help.
Steve

Resources