ASP.NET MVC Model confusion - c#

Background
I'm learning the ropes around how to use ASP.NET MVC properly, and ran into this issue with models:
I have a model that describes a contact I can get that out of the form for creating a new contact, but say when we edit a form, I retrieve it from the repository, show the fields on the contact form and then get the contact object and send that to the model.
Problem
I have a business rule that some fields are not allowed to be edited after creation and other fields are only available after editing.
I receive a dirty object from the user (one with fields they should touch) and using the MVC Binding method (sspecifying the object in the method signature) the users inserts a non-editable field contact_dob.
Question
Should I instead retrieve the record again, overwrite only the fields I want to update and then send it to the database?
What's the best method when I don't want to retrieve the Entire object again from the database, do I just redo another EntityModel that's a lighter version of the main model and use that back and forth?
Am I going about this the wrong way? What are the best practices for limiting what users can edit?

I think you can build your model, the Contact class, and in the edit view you should allow only fields that can be edited, and hide or set as not editable the fields you don't want to be edited, then in your controller you'll get the original contact and update it with the values of the fields you allowed in the edit view like:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues) {
Contact contact = repository.GetById(id);
try {
UpdateModel(contact);
repository.Save(contact);
return RedirectToAction("Details", new { id=contact.Id });
}
catch(Exception ex) {
// Do something...
}
return View(contact);
}

It sounds like the best solution would be to use a custom ViewModel. This is an object that contains all the fields that you would want the user to submit to the controller.
You will need to reload the contact object from the database - I don't think you can get around that without opening yourself up to other issues.
public ActionResult Edit(ContactViewModel viewModel)
{
var contact = repository.GetContacts().WithId(viewModel.Id);
// Update the contact with the fields from the viewModel
repository.Save(contact);
}

You should use the EXCLUDE and INCLUDE constraints in Action method. This way your model will exclude unwanted fields during model binding.
public ActionResult Create([Bind(Exclude="contact_dob")] Contact contact)
{
_db.AddToContacts(contact);
_db.SaveChanges();
return RedirectToAction("Index");
}

The 'best practice' is to have validation done against your submitted model and not allow changes to certain fields. You can use JQuery / JavaScript to grey out textboxes that cannot be changed; as well as validation on the Model side to disallow changes to certain fields (by comparing them against what came from the database).
You can use Model Validation to disallow changes to certain fields. ASP.NET MVC 2 has this functionality. You don't even need to re-retrieve the object.
In the 'NerdDinner Walkthrough' (ASP.NET MVC 1.0), there's a walkthrough of Validation.

Related

Updating Controller and Views after adding column to Model

I am new to Entity framework, so this is probably a stupid question.
I have added a new field to a Model class. I have created the migration and updated the database and this all works as expected. The new column has appeared in the SQL table.
I have manually modified the Create/Details Views (I'm guessing this isn't automatic) to include the new column. The new column is called "Level".
However, my Controller class doesn't seem to have picked up the changes. It doesn't insert the value when creating a new row. There are references to column names in the Controller class, but the new column name isn't there. E.g.
public async Task<IActionResult> Create([Bind("Id,Name")] Course course)
Is there any way to "refresh" the Controller to pick up the changes? Or will I have to manually edit the lines where the columns are named and add the new column?
If your view has a control bound to this new Level field and you want to pass it to the controller to write, then you will need to add it to the Bind attribute:
public async Task<IActionResult> Create([Bind("Id,Name,Level")] Course course)
While it might look like when you pass a Model to a view, and have a Form in the view that calls an action on the Controller passing that Model back, this isn't actually what happens. ASP.Net MVC is merely formatting the code in that way. Honestly this is a bit of a bad practice when using EF Entities as it trips up quite a few developers expecting that Entity references are being passed between server and view. It leads to confusing problems and is also an open door to data tampering when used incorrectly.
When the controller passes the Model to the View(), it is passing that Model to the View Renderer to compose the HTML view that will be sent to the browser. So if you're passing a Course entity, that entity does not travel to the client, it is consumed by the Server to build the HTML.
When your Form goes to call the controller, it will automatically append any bound fields that it knows about. This will include any bound entry controls, and if there are any details that don't have edit controls bound to them, you need to use bound Hidden controls to ensure that the MVC Javascript knows to pick those up too.
If you use a Bind attribute, this tells MVC which properties coming back from a Form submit or Ajax call that you actually want to accept. If "Level" isn't in there, the value will be ignored even if passed. The View does not pass an actual entity, it will be a set of named parameters that MVC has some magic smarts to convert into a Model object based on convention.
The Action could be written as either:
public async Task<IActionResult> Create([Bind("Id,Name,Level")] Course course)
or
public async Task<IActionResult> Create(int id, string name, string level)
where in the second case you'd need to handle the creation and population of your Course entity using the values passed in.

asp.net mvc ViewState implementation

I working on a web project where I first get data from the database and bind to the Html control. If there is a validation error I will send the same view back for rendering with the displayed validation errors. When the page comes up, there is an exception. I stepped through the code and found that the model was passed will null collection. Basically any property that was not binded to a textbox was changed to null. I was told not to use session or viewdata to keep temp storage. So I call a method SaveViewState where it save all the property value of the ViewModel property to a static variable like so
private static MyViewModel _viewModel;
private MyViewModel SaveViewModel(MyViewModel viewModel)
{
if (_viewModel == null)
{
_viewModel = new MyViewModel ();
}
if (!string.IsNullOrEmpty(viewModel.MyName))
_viewModel.MyName= viewModel.MyName;
if (!string.IsNullOrEmpty(viewModel.Number))
_viewModel.Number= viewModel.Number;
if (!string.IsNullOrEmpty(viewModel.Address))
_viewModel.Address= viewModel.Address;
if (!string.IsNullOrEmpty(viewModel.State))
_viewModel.State= viewModel.State;
}
It works but I think it is very inefficient and there must be a better way to implement ViewState in MVC with Session or ViewData or HiddenFields? By the way, I was told not to use those three.
Any help is appreciated. Thanks.
I am not sure if this solution is worse than using a session or hidden fields. In your action you should return the corresponding view with the same model that was posted. The ActionResult should be something like this:
public ActionResult SomePost(SomeModel model)
{
if (!ModelState.IsValid())
{
//error in validation
return View(model);
}
//post save redirect and stuff
return ... redirect?
}
The ModelState.IsValid() will test according to the DataAnnotations. Standard attributes like [Required], [MaxLength] etc. are available.
In this configuration, the use of a SaveViewModel function is not required. If your collection is null after post: re-query it, post it or fetch it from a ViewData like object.
There are good reasons not to use those three you mentioned, but if you know that reason you might want to consider it:
1) Use of session: will make scalability difficult because every request in a session must hit that specific server.
2) Hidden fields: Not really a problem IFF you realize the hidden field can be manipulated in a browser. So don't store ID's there
3) ViewData: basically breaks the MVC pattern; you can use it to store data but that's what a model is for. It totally legitimate to use ViewData from a filter. To provide some general functionality for example.

Keep data in ViewModel when validating in MVC5

In my asp.NET MVC5 app I have a controller that supplies a view which is strongly typed vs a viewmodel. This viewmodel has a SelectList property (among others), and the controller supplies the data on creation from the database:
public ActionResult Simulation() {
var SimVM = new SimulationVM(
StrategyRepository.GetStrategies().Select(n => n.Name),
);
return View(SimVM);
}
The SelectList is then used as data source for a DropDown choice in a form. The HttpPost method does some datavalidation, i.e.,
[HttpPost]
public ActionResult Simulation(SimulationVM _simVM) {
if (ModelState.IsValid) {
// ...
}
else return View(_simVM);
}
So with the code above, the DropDown data is empty, since on posting, the SimulationVM object is created new. The usual trick of using Html.HiddenFor does not work on collections.
Of course, I could go back and fetch the data again from the database, but that seems to be bad, a database fetch for such a simple thing as a validation where I know the data hasn't changed.
What is the best (or for the sake of not being subjective: any) way to keep some data in the ViewModel (or repopulate it efficiently)?
If it is a requrement that you not go back to the database and you're 100% confident that the data will not change (i.e. this is a list of states as opposed to a list of orders or something) then you can add the collection to a session variable. Here's a link to a decent article:
https://code.msdn.microsoft.com/How-to-create-and-access-447ada98
That being said, I usually just go to the database and get the data again. If doing so for a second time is causing huge performance issues, it is most likely causing performance issues the first time and you should treat the problem rather than the symptom.

How do I create a form in asp.net MVC 5

I'm used to web forms, but am switching to MVC 5 and have a question about creating a multi step application form.
This form is like a wizard then will display information entered in each step at the end, then submit.
Is it easier to write this using html form in the .cshtml or do it all in the controller?
THank you
MVC, as its name suggests, has a Model, a View, and Controller. To create a form, you set up a class that will act as your Model, containing the properties that need to be worked with in a particular view. This is a different thing than your entity, the class that corresponds to a table in your database. You can sometimes use the entity as the Model, but especially in the case of a multi-step form, you don't want to persist the data until the end, which means, they'll need to be separate.
This brings us to the topic of view models, which is actually from another different pattern called MVVM. Regardless, your Model for these views will be a series of view models that contain just the information that the particular step needs to collect. At the end, you will piece all of the collected data together by creating an instance of your entity and mapping the property values from each view model over to it. Then, you will save the entity.
Now, as far as persisting the collected data between requests goes, that's where your session comes in. You'll merely add each posted view model into your Session object, and then at the end, fetch all of them from the Session object to create your entity.
So each POST action will have something like the following:
[HttpPost]
public ActionResult Step1(Step1ViewModel model)
{
if (ModelState.IsValid)
{
Session["Step1"] = model;
return RedirectToAction("Step2");
}
// errors
return View(model);
}
Then, your final POST action:
[HttpPost]
public ActionResult StepFinal(StepFinalViewModel)
{
if (ModelState.IsValid)
{
var myEntity = new MyEntity();
var step1 = Session['Step1'] as Step1ViewModel;
myEntity.SomeField = step1.SomeField;
// ... repeat for field in view model, then for each step
db.MyEntities.Add(myEntity);
db.SaveChanges();
Session.Remove('Step1');
// repeat for each step in session
return RedirectToAction("Success");
}
// errors
return View(model);
}
All of your form information will be in the .cshtml file like this:
#using (Html.BeginForm("Controller Action Method", "Controller Name", FormMethod.Post, new { id = "Form Name" }))
{
// Form Elements here
}
Then you can simply add a submit button that submits the form to your Controller for processing.

Refresh ModelState to remove errors

Refreshing the ModelState
Hi, I have a question about the ModelState in an ASP.NET MVC controller.
When the user selects a certain option from the view, the start date and end date for the "certification" will be set based on the other dates entered.
The problem with this is the certification dates come back as null and our CertificationMetaData class specifys the fields as [Required] so the ModelState is invalid as soon as the action loads.
Removing the ModelSate errors manually allows this to work but I was wondering if there is a better way to do this? Is there a way to refresh the ModelState? Should I make the fields not required? Or should I add a date value from the view with javascript?
public ActionResult Create(FormCollection fc, Certification certification, Absence absence)
{
if (certification.CertificationTypeID == 1)
{
certification.CertificationStartDate = absence.StartDate;
certification.CertificationEndDate = absence.StartDate.AddDays(7);
this.ModelState.Remove("CertificationStartDate");
this.ModelState.Remove("CertificationEndDate");
}
if (this.ModelState.IsValid)
{
// save
return RedirectToAction("Index");
}
return View();
}
Also as you can see I have hardcoded the ID value for the certification type. What is the best way to compare values with lookup table values? Is an enum the best way to go?
Thanks
The following approach refreshes the model state and allows you to keep your model design consistent with [required] attributes etc.
In my case I want my model to have a required field that normal level users using an API can't change, so I've done this:
ModelState.Remove("ChangeDate");
ModelState.Add("ChangeDate", new ModelState());
ModelState.SetModelValue("ChangeDate", new ValueProviderResult(club.ChangeDate, DateTime.Now.ToString(), null));
That way you don't need to remove your required fields, and you also don't need to supply a date in javascript.
Obviously this is a personal thing, but I wouldn't remove the error messages.
If I was going for the simple solution then I would remove the [Required] attribute and add validation code to the controller to add the error if the dates were missing or set them to the alternate value if it was the correct type.
If I was going for the more complex solution I would put the validation at the Model level. Possibly a base class or and interface that the model must implement. A ValidationHelper class with a static Validate(IValidate object) method that will inspect the ValidationAttributes and calls a Validate method on the Model. It would then return a collection of ValidationErrors. Then a custom ModelBinder would be written that understands the Model validation and maps these to ModelState errors.

Categories

Resources