MVC4 - getting list of fields in View - asp.net-mvc

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.

Related

Should I use a view model for just two objects?

Lets say I have a view that accepts a Person object.
Has three properties, FirstName, LastName, Age
Now lets say I add another textbox field that's not part of the object.
I don't need the value of the textbox, its just populated with data that's for the user.
When you edit the fields and post the Person to the controller, lets assume there is a validation problem so you return the Person object back with Errors
The problem is now the additional textbox has lost it's value since its not part of the model.
So I made a ViewModel with a string property for that field and a Person property to keep all the values. Seems like there would be a better way to keep the value in the "special" textbox?
You should be able to get that extra field from the posted fields. How do you set it first time, through the ViewBag? You should be able to set it again.
But what exactly is wrong with using a ViewModel? Sooner or later you will have 2 or 3 extra fields, or a Person and an Appointment.
I think that's totally the right way to do it. The viewmodel is the model for the view not the model for your non-UI processing, it contains a Person and extra viewable information. It fits exactly with the concept. Your Person is presumably a (non-view) model and therefore when you have a valid post back, you get the Person to save it's data (or whatever) and the extra viewable information is irrelevant at that point, because you are no longer in a 'View/UI' part of your app.
Make the view strongly typed to your viewmodel and access the Person within it
#model myViewModel
#Model.Person.FirstName
#Model.OtherViewOnlyValue
Go with the viewmodel, so much cleaner than ViewBags/Session/ViewData etc.
There are many times that you might think that you do not need to include a UI mapping to a ViewModel but most of the time you will end up adding the mapping into the ViewModel. I believe that ViewModel should represent everything on your UI screen. Since HTTP is stateless the post form values will play an important role in populating the user interface controls.

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.

ASP.NET MVC save new record verse update existing record conventions

I'm working on my first ASP.NET MVC (beta for version 3) application (using EF4) and I'm struggling a bit with some of the conventions around saving a new record and updating an existing one. I am using the standard route mapping.
When the user goes to the page /session/Evaluate they can enter a new record and save it. I have an action defined like this:
[ActionName("Evaluate")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EvaluateSave(EvaluteSessionViewModel evaluatedSession)
{
}
When they save I grab an entity off the view model and attach it to my context and save. So far, so good. Now I want the user to be able to edit this record via the url /session/Evaluate/1 where '1' is the record ID.
Edit: I have my EF entity attached as a property to the View Model.
If I add an overloaded method, like this (so I can retrieve the '1' portion automatically).
[ActionName("Evaluate")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EvaluateSave(ID, EvaluteSessionViewModel evaluatedSession)
{
}
I get an "The current request for action 'Evaluate' on controller type 'SessionsController' is ambiguous between the following action" error. I'm not sure why they're ambiguous since they look unique to me.
I decided that I was just going to skip over this issue for now and see if I could get it to update an existing record, so I commented out the EvaluateSave that didn't have the ID parameter.
What I'd like to do is this:
// Load the original entity from EF
// Rebind the postback so that the values posted update the entity
// Save the result
Since the entity is populated as the parameter (evaluatedSession) the rebinding is happening too soon. But as I look at the approach I'd like to take I realized that it opens my code up to hacking (since a user could add in fields into the posted back page and these could override the values I set in the entity).
So it seems I'm left with having to manually check each field to see if it has changed and if it has, update it. Something like this:
if (evaluatedSession.MyEntity.myField <> savedSession.myField)
savedSession.myField = evaluatedSession.MyEntity.myField;
Or, save a copy of the entity and make sure none of the non-user editable ones have changed. Yuck.
So two questions:
First: how do I disambiguate the overloaded methods?
Second: is there a better way of handling updating a previously saved record?
Edit: I guess I could use something like Automapper...
Edit 9/22/2010 - OK, it looks like this is supposed to work with a combination of two items: you can control what fields bind (and specifically exclude some of them) via the [Bind(Exclude="field1,field2")] attribute either on the class level or as part of the method doing the saving, ex.
public ActionResult EvaluateSave([Bind(Exclude="field1")] EvaluateSessionViewModel evaluatedSession)
From the EF side of things you are supposed to be able to use the ApplyCurrentValues() method from the context, ex.
context.ApplyCurrentValues(savedEval.EntityKey.EntitySetName, evaluatedSession);
Of course, that doesn't appear to work for me. I keep getting "An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied.".
I tried attaching the original entity that I had just loaded, just in case it wasn't attached to the context for some reason (before ApplyCurrentValues):
context.AttachTo(savedEval.EntityKey.EntitySetName, savedEval);
It still fails. I'm guessing it has something to do with the type of EF entity object MVC creates (perhaps it's not filled in enough for EF4 to do anything with it?). I had hoped to enable .NET framework stepping to walk through it to see what it was attempting to do, but it appears EF4 isn't part of the deal. I looked at it with Reflector but it's a little hard for me to visualize what is happening.
Well, the way it works is you can only have one method name per httpverb. So the easiest way is to create a new action name. Something like "Create" for new records and "Edit" for existing records.
You can use the AntiForgeryToken ( http://msdn.microsoft.com/en-us/library/dd492767.aspx ) to validate the data. It doesn't stop all attempts at hacking but it's an added benefit.
Additional
The reason you can only have one action name per httpverb is because the model binders only attempt to model bind and really aren't type specific. If you had two methods with the same action name and two different types of parameters it can't just try and find the best match because your intent might be clearly one thing while the program only sees some sort of best match. For instance, your might have a parameter Id and a model that contains a property Id and it might not know which one you intend to use.

ASPNET MVC what do you call this, a partial view? Or something else?

I'm trying to google for info on a situation, but I dont know what it is called, so its hard to find results :)
I have a model with say 10 fields. But only some of those are shown on a particular view, lets say 3 of them: id, name, date. What do you call this kind of view that does not display the whole model? A partial view?
The problem is that because 7 fields are not sent to the view, when the Update action is called on the controller, those fields are null, and the DB gets updated with those 7 fields set to null.
This is called a ViewModel, which is obtained from the Model and is more adapted to the View.
This is still a view.
You are not specifying what kind of storage are you using, I'll make an example using the entity framework, but you can do it with whatever method you like.
The model for the view is an Entity. When you display the form in your view, only part of the fields in your model are editable. When the user submits, therefore, your model has only several fields filled in.
So, you should retrieve a new copy of the object you are editing from the database (call it "fromDb"), copy only the edited fields into the fromDb object, and save the fromDb object instead.
This way, all the fields are preserved.
Another way to do this, is to render hidden fields for all the fields that are not present. However this is NOT secure, as the user could edit those fields by hand (using the developer tools, or firebug).

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