MVC 5 Bind Implement with all Parameters - c#

So MVC5 has brought in that new Bind attribute, to my knowledge it is used to specify which properties of the parameter object that should be bound to. Also, this is a security measure to help prevent XSS and Model Binding attacks. Most tutorials show it in action against a model.
public async Task<ActionResult> Create ([Bind(Include="Id,Description,IsDone")] ToDo todo)
In my applications I only ever pass view models to and from controllers and views:
[HttpPost]
public ActionResult Create(UserViewModel vm)
{
}
Should I also use this technique here?
[HttpPost]
public ActionResult Create([Bind(Include="property, property2")]UserViewModel vm)
{
}
In all honesty there are very few times where I don't want to bind to every property in the view model.
Firstly, is my understanding of the Bind attribute accurate?
Secondly, is my understanding of when to use the Bind attribute accurate?

You're spot on!
You're also spot on!
You've got a good understanding of what the attribute is intended for. Only you can prevent forest fires know if you should use the attribute. If you're building a data-sensitive application you absolutely want to protect yourself from over posting. If you're building an internal low-risk application, perhaps you can skip the magic strings, trust your users, and not deem it worth your time.
The ASP.NET website has more information about over posting.

Related

Using httpget when no data is changed?

I remember reading & have been told you should only use [httppost] on controller actions that may change data (I can't find these sources though - and am unable to find anything on Google).
And if you are - say, just doing a lookup of data you should use [httpget].
I have 2 controller actions - used only for looking up data, never for changing it.
I have tried using two [httpget]s this in an ASP.NET MVC 5 controller:
public ActionResult MyAction(Guid Id)
{
// Id is used to populate the form
}
// I would previously have placed [httppost] here
public ActionResult MyAction(MyObject myobj)
{
// myobj is posted back from the form - but no data is changed in the database, it's just a lookup
}
However, I get this error:
The current request for action 'MyAction' on controller type
'MyController' is ambiguous between the following action methods:
The compiler is having a problem with ambiguous method names - so what is best practice for doing this?
Do we have to use a form specifying an explicitly different action? (this seems inelegant and messy - it makes [httppost] look simpler, more elegant and more terse if that is the case).
Is it indeed the case that we should use [httpget] in situations where no data is being persisted?
thx.
Your problem is that you have two methods with the same name in your controller. And action resolver can not decide which one to use.
Easiest way is to follow naming convention, in this case you won't have to put attributes:
public ActionResult GetMyAction(Guid Id)
{
// Id is used to populate the form
}
// I would previously have placed [httppost] here
public ActionResult PostMyAction(MyObject myobj)
{
// myobj is posted back from the form - but no data is changed in the database, it's just a lookup
}
However if you want to stay with your names, you will have to put appropriate attributes:
[HttpGet]
public ActionResult GetMyAction(Guid Id)
{
// Id is used to populate the form
}
// I would previously have placed [httppost] here
[HttpPost]
public ActionResult PostMyAction(MyObject myobj)
{
// myobj is posted back from the form - but no data is changed in the database, it's just a lookup
}
I think you're misunderstanding the rationale for get vs post. The important thing is not that post requests always change the state, the important thing is get requests never change state. One great example was a content management system that regularly experienced their content inexplicably disappearing before figuring out that a web crawler was indexing an admin page and following their deletion hyperlinks, all using http get, or prefetching browsers randomly adding or removing shopping cart items.
That said, I'd probably still make both of these gets using different actions, because the get verb better describes the service action, but maybe you have good reasons not to do that.

Where is a good place to put common business logic that should run on every view?

I have a project in which I need to check for and add a cookie, regardless of which view the user is currently on. I can place the code inside of the _Layout partial view within a code block, but I have doubts that's the conventional place for it. Where should it go?
View is generally wrong place to put logic.
Action filter is one possible way to centralize the code and allow easy customization, especially for something that sound so close to behavior of AuthorizeAttribute filter.
See Action Filtering in ASP.Net MVC for information.
public class MyCookieFilter : ActionFilterAttribute ...
[MyCookieFilter]
public ActionResult Index()
{
// The action method logic.
}
Side note: when searching for documentation be carefull to distinguish MVC and WebAPI classes - many have similar names and similar behavior, but can cause some confusion when applied to wrong objects.

ASP.net MVC - One ViewModel per View or per Action?

Is it a better idea to have a single ViewModel per view or one per controller action?
Example:
public ProjectController : Controller
{
public ActionResult Edit(int id)
{
var project = ...;
return View(new ProjectEditViewModel(project));
}
[HttpPost]
public ActionResult Edit(ProjectEditViewModel model)
{
}
**OR**
[HttpPost]
public ActionResult Edit(Project model)
{
}
[HttpPost]
public ActionResult Edit(ProjectEditPostViewModel model)
{
}
}
Here are the three options, which is best?
Use the same ViewModel for my POST/GET actions.
Use a ViewModel for my GET action and my domain model for my POST action.
Use a different ViewModel for GET and a different ViewModel for POST.
Using a different view model for the GET and POST actions is the best and most flexible design. But using the same view model for the GET and POST actions also works in 90% of the cases and it is fine a good design. So if using the same view model works in your scenario don't hesitate to reuse it like this.
In the case where different view models are used for the GET and POST actions there is still some relation between those classes: inheritance or composition.
The correct answer
Neither. There's no silver bullet and shouldn't be.
The correct answer is therefore: use as many view models as your user interface process demands. That's regardless of views or controller actions.
Sometimes an action demands a view, other a view. But don't follow some strict guidelines that would hinder your development. View models will come naturally as you develop your application. And should. Otherwise you may end up with unreasonable views that are based on some guideline you've set in stone.
This is actually a similar answer as #DarinDimitrov's, but with a direct conclusion.
Use different model to receive input parameters in Post action (I don't even call it ViewModel in that case) than to pass output parameters to the view.
That way you can customize exactly what input parameters do you accept.
I follow this approach for basic forms:
One view model for the GET
One view model for the POST
The GET model inherits the POST model.
I will often pass a domain object to the GET model's constructor, and do 2 things with it:
Populate the POST model properties with data from the domain object.
Encapsulate the domain object as a local variable in the GET model. I use this for displaying some (read-only) data from the domain object. Saves a bit of effort. Some people will tell you not to do this.

ASP.NET MVC3 - How to serve View() from another controller

So in order accomplish what I asked in this post I did the following:
[iPhone]
[ActionName("Index")]
public ActionResult IndexIPhone()
{
return new Test.Areas.Mobile.Controllers.HomeController().Index();
}
[ActionName("Index")]
public ActionResult Index()
{
return View();
}
Which still serves the same view as the Index action method in this controller. Even though I can see it executing the Test.Areas.Mobile.Controllers.HomeController().Index() action method just fine. What's going on here? And how do I serve the Index view from Mobile area without changing the request URL (as asked in the original post referenced above)?
You have a few options:
Redirect to the Action you'd like to return: return RedirectToAction("Action-I-Want").
Return the View by name: return View("The-View-I-Want").
Note that with the 2nd approach you'd have to put your view in the "Shared" folder for all controllers to be able to find it and return it. This can get messy if you end up putting all your views there.
As a side note: The reason your work doesn't find the view is because default view engine looks for the view in the folder that "belongs" to the current executing controller context, regardless of what code you're calling.
Edit:
It is possible to group all "mobile" views in the same folder. On your Global.asax (or where ever you're setting up your ViewEngine, just add the path to your mobile View in the AreaViewLocationFormats. Mind you, you'll still have to name your views differently.
You can also write your own view engine. I'd do something like detecting the browser and then serving the right file. You could setup a convention like View.aspx, and View.m.aspx.
Anyhow, just take a look at WebFormViewEngine and you'll figure out what works best for you.
The easiest way to send a request to a view handled by another controller is RedirectToAction("View-Name", "Controller-Name").
There are overloads of View() that take route information that might work as well, but they'd require more effort to set up.
Well actually the easiest way is to make one version of your site programmed on standards instead of browser detection :D -- however in direct response to accomplish what it in a more of a ASP.NET mvc fashion, using:
RedirectToAction("ViewName", "ControllerName");
is a good method however I have found it is more practical if you feel you must program for different browser standards to create a primary view and an alternate "mobile" view under your controllers views. Then instead of writing special code on every controller, instead extend the controller like so.
public class ControllerExtended : Controller
{
private bool IsMobile = false;
private void DetectMobileDevices(){ .... }
}
Then modify your controller classes to instead say ControllerExtended classes and just add the one line to the top of each Action that you have alternate views of like so:
public class ApplicationsController : ControllerExtended
{
// GET: /Applications/Index
public ActionResult Index() {
this.DetectMobileDevices();
if(this.IsMobile){
return RedirectToAction("MobileIndex");
} else {
// actual action code goes here
return View();
}
}
}
Alternately you can use return View("ViewName"); but from my experience you want to actually perform different actions as opposed to just showing the result in a different view as in the case of presenting an HTML table as opposed to a Flex table to help iPhone users since there is no flash support in the iPhone, etc. (as of this writing)

how can i keep my url when my validation fail in asp.net mvc controller action

if i start off on a Detail page:
http:\\www.mysite.com\App\Detail
i have a controller action called Update which normally will call redirectToAction back to the detail page. but i have an error that is caught in validation and i need to return before redirect (to avoid losing all of my ModelState). Here is my controller code:
public override ActionResult Update(Application entity)
{
base.Update(entity);
if (!ModelState.IsValid)
{
return View("Detail", GetAppViewModel(entity.Id));
}
return RedirectToAction("Detail", new { id = entity.Id })
but now I see the view with the validation error messages (as i am using HTML.ValidationSummary() ) but the url looks like this:
http:\\www.mysite.com\App\Update
is there anyway i can avoid the URL from changing without some hack of putting modelstate into some temp variables? Is there a best practice here as the only examples i have seen have been putting ModelState in some tempdata between calling redirectToAction.
As of ASP.NET MVC 2, there isn't any such API call that maintains the URL of the original action method when return View() is called from another action method.
Therefore as such, the recommended solution and a generally accepted convention in ASP.NET MVC is to have a corresponding, similarly named action method that only accepts a HTTP POST verb. So in your case, having another action method named Detail like so should solve your problem of having a different URL when validation fails.
[HttpPost]
public ActionResult Detail(Application entity)
{
base.Update(entity);
if (ModelState.IsValid)
{
//Save the entity here
}
return View("Detail", new { id = entity.Id });
}
This solution is in line with ASP.NET MVC best practices and also avoids having to fiddle around with modestate and tempdate.
In addition, if you haven't explored this option already then client side validation in asp.net mvc might also provide for some solution with regards to your URL problem. I emphasize some since this approach won't work when javascript is disabled on the browser.
So, the best solution would be have an action method named Detail but accepting only HTTP POST verb.
The problem here is actually caused by your implementation. This doesn't answer your question, but it describes where you've gone wrong in the first place.
If you want a page that is used to update or edit an item, the URL should reflect this. For example.
You visit http:\www.mysite.com\App\Detail and it displays some information about something. That is what the URL describes it is going to do. In your controller, the Detail() method would return the Detail.aspx view.
To edit an item, you would visit http:\www.mysite.com\App\Edit and change the information you wish to update, the form would post back to the same URL - you can handle this in the controller with these methods:
[HttpGet]
public ActionResult Edit() {
MyModel model = new MyModel();
...
return View(model);
}
[HttpPost]
public ActionResult Edit(MyModel model) {
...
if (ModelState.IsValid) {
// Save and redirect
...
return RedirectToAction("Detail");
}
return View(model);
}
If you ever find yourself doing this...
return View("SomeView", model);
You are making your own life harder (as well as breaking the principles behind URLs).
If you want to re-use part of a view, make it a partial view and render it inside of the view that is named after the method on the controller.
I apologise that this potentially isn't very helpful, but you are falling into an MVC anti-pattern trap by displaying the same view from a differently named method.
As #Malcolm sais, best practice is to put ModelState in TempData, but don't do it manually! If you'd do this manually in every controller action where it's relevant, you would introduce immense amounts of repeated code, and increase the maintenance cost vastly.
Instead, implement a couple of attributes that do the job for you. Kazi Manzur has an approach (scroll down to the end of the post) that has been widely spread, and Evan Nagle shows an implementation with tests that is essentially the same as Kazi's, but with different names. Since he also provides unit tests that make sure the attributes work, implementing them in your code will mean little or no maintenance cost. The only thing you'll have to keep track of is that the controller actions are decorated with the appropriate attributes, which can also be tested.
When you have the attributes in place, your controller might look something like this (I deliberately simplified, because I don't know the class you inherit from):
[HttpPost, PassState]
public ActionResult Update(EntityType entity)
{
// Only update if the model is valid
if (ModelState.IsValid) {
base.Update(entity);
}
// Always redirect to Detail view.
// Any errors will be passed along automagically, thanks to the attribute.
return RedirectToAction("Detail", new { id = entity.Id });
}
[HttpGet, GetState]
public ActionResult Detail(int id)
{
// Get stuff from the database and show the view
// The model state, if there is any, will be imported by the attribute.
}
You mention that you feel putting ModelState in TempData feels like a "hack" - why? I agree with you that doing it with repeated code in every single controller action seems hacky, but that's not what we're doing here. In fact, this is exactly what TempData is for. And I don't think the above code looks hacky... do you?
Although there are solutions to this problem that might appear simpler, such as just renaming the action method to preserve the URL, I would strongly advise against that approach. It does solve this problem, but introduces a couple of others - for example, you'll still have no protection against double form submission, and you'll have pretty confusing action names (where a call to Detail actually changes stuff on the server).
The best practice you ask for is actually what you explained not to do: putting modelstate into tempdata. Tempdata is meant for it, that's why I would not call it a hack.
If this is to much repetitive code you could use the attribute modeldatatotempdata of MVCContrib. But the store is still TempData.

Categories