ASP.NET MVC controllers best practice for method naming [closed] - asp.net-mvc

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I know next to nothing about MVC so my question might look a bit basic but here it is anyway : is it a good practice to have the same name for the method returning the view and the one saving the data ?
I see a lot of examples like this one where the overloaded "Create" does both jobs. Here's a snippet:
//
// GET: /Customer/Create>
public ActionResult Create()
{
return View();
}
//
// POST: /Customer/Create>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here>
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I personnaly find it confusing when overloads do completely different things depending on which I decide to choose. So what do you think ? Is it really the "best practice" to roll that way?

Yes, the GET and the POST in this case usually share the same name, because they relate to the same user action.
See Action Naming Convention for more guidance on Action naming.

I personally find it confusing when overloads do completely different things depending on which I decide to choose.
Do they really? They are both concerning the same entity (a Customer). What you can do is name methods whatever you want and then add the [ActionName] attribute and that will be the name of the action. But yes. it's an MVC convention to name them the same way and then pick one or the other depending on whether you're using GET or POST.

Yes if it is the POST method for that view then you should stick to the same name. The only time you should not follow this convention would be if you have multiple different POST methods for the same view for some reason or if you have a POST method which is used by multiple different views.
To provide a standard example:
You have a Create view which is used to create users. There is a HTTPGET Create() action and a HTTPPOST Create() action for posting the user details to the server. In this case you should use the same name.
You have a Dashboard view which displays some data from the database. You have some javascript which uses ajax to retrieve data from the server. In this case you may consider using a different name. E.g. GetData()

Related

How do I the site logo depending on the URL the request was made from? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I created a product registration page using ASP.Net MVC. I need to implement the same product registration page for subsidiaries (maybe 3 or 4) with a few minor changes to the way the site looks. For example, the logo will be different and some text at the top of the page. What is the best way to use the same codebase?
The best option I could come up with is passing HttpContext.Current.Request.URL to the view and using java script to update it.
However, I know routing can be an option too.
If you will be keeping the same .cshtml view for all registration pages then i think creating a partial view for logo generation would probably help you out.
Add another variable to your view model.. maybe call it subsidiary?
public int Subsidiary { get; set; }
then create a partial view called something like _LogoPartial.cshtml and in there do a if statement on the Subsidiary variable and return a different logo based on it
#model int
#if (Model == 1)
{
<img src="something" />
}
else if ...
then in your main view call it with
Html.RenderPartial("~/Views/Shared/_LogoPartial", Model.Subsidiary);

Redirect to Action in another area that accepts a model [duplicate]

This question already has answers here:
Can we pass model as a parameter in RedirectToAction?
(6 answers)
Closed 7 years ago.
There are a few questions on SO about redirecting to an action in another area but none answers a more specific question that I have.
Let's say I have an Action like this:
public virtual ActionResult ActioName(ViewModel model)
{
return View(model);
}
If there wouldn't be a model parameter, you would do the following to redirect to this action from another area:
return RedirectToAction("ActioName", "ControllerName", new { Area = "" });
I tried including a model as well as the area in multiple ways but didn't work. I need a way to include both the area name and model.
Thank you.
EDIT: TempData is not an answer, I do not want to modify the target controller.
Use RedirectToRoute instead, where namedRoute provides the controller name and action instead of retrieving from the url, like the default route does.
return RedirectToRoute("namedRoute",model);
Or possibly:
return RedirectToRoute("namedRoute",new { model: model });
Or to redirect into an area
return RedirectToRoute("Area_namedRoute",model);
Just be aware that this will trigger a get request instead of a post. That has a few limitations to be aware of:
Browsers have limitations on the length of a url, IE being more troublesome here
Actions methods with [HttpPost] attributes can't be triggered this way
Embedding large amounts of data in a url is a security risk. What happens if a user shares their web page with a friend.
Get requests are considered by search engines to be free from side-effects, they are considered read-only.
That being said, see ASP.NET MVC: RedirectToAction with parameters to POST Action if you need to post instead of get.

why returning to other view from action is bad? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I m working in MVC and some one recently has reviewed my code. On some places in my controller actions I was returning to other views, for example in below code in Index action I m returning to List view:
public virtual ActionResult Index(Student student)
{
// Logic
return View("List", student);
}
Why it is not a good practice ? I did not get any idea why this is wrong. Kindly guide me so I can correct this.
There is nothing wrong with returning a different view to the default action view. The only thing I can think that might be unsettling to some is it does not following the MVC paradigm of convention over configuration.
This may make it difficult to follow someones code if they have lots of actions with names that are different to their corresponding view names i.e:
public ActionResult Index(int id)
{
//logic
return View("StupidName");
}
Convention would have you think the index action would return the Index view, although it doesn't and now the programmer has to go look for the StupidName view. This may seem harmless for one action but if someone has written multiple actions that return differently named views it can be difficult to follow the flow of the project.
Alternatively you could ask the code reviewer why he thinks it is a bad practice. Communication is key in a team.
Personally I see nothing wrong with this as long as the logic for compiling the input for the view isn't duplicated.
If you have to copy a lot of code to ensure that the model for the view is correct, and this isn't really the responsibility of your action, you'd rather redirect to the action instead of calling the view directly.
If this is not the case, or there is a very specific situation, I don't see why this is a problem.
Consider these examples:
You have a error dialog view. If the model just consists of a single property defining the message, it is no problem to call the view directly;
If you have the same dialog, but in order to create the model you have to fetch some general information from the database, have some custom logic, etc., then it is probably best to call the (or create an) action doing this all for you. Also, the number of calls to that view may matter in your decision.
Try this :
public virtual ActionResult Index(Student student)
{
// Logic
return RedirectToAction("List");
}

MVC multiple data-models passed to a view [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
ASP.NET MVC - View with multiple models
Using ASP.NET MVC 3.0, how can I pass multiple data models from my controller to my view? I'm hoping for an elegant solution...thanks!
BTW - I can provide code samples but I think this is generic enough not to warrant it
There isn't a truly elegant way to do it, unfortunately. My preferred method is to encapsulate the two objects and send that to the view.
public class City{
public Mall TheMall;
public School TheSchool;
}
Then your view will be strongly typed as City, and you will use Model.TheMall.Property and Model.TheSchool.Property to access what you need.
Another method is to use the ViewData bag. What you can do is populate it like such:
ViewData["City"] = "Toronto"; //random string
ViewData["Mall"] = new TheMall(...);
return View(MyViewName);
And then in your view, you will have access these using the key you assigned in the controller ("City", "Mall", in this case).
Hope that helps!

ASP.NET MVC: Is a helper allowed to grab data? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
All my controllers in my project inherit from a base controller, which has a property with my Entity Model.
Let say I have a view that shows cities in the world, and it has an option to filter by country. The country filter is a dropdown list of countries from the database. The Html helper for the dropdown list requests a IEnumerable<SelectItem>.
Now with that info, is it ok if I create a HtmlHelper that looks like this:
public static IEnumerable<SelectListItem> GetCountries(HtmlHelper htmlHelper)
{
return (from c in ((BaseController) htmlHelper.ViewContext.Controller).Entities.Countries
orderby c.Name
select new SelectListItem() {Text = c.Name, Value = c.ID});
}
The question is not if I it is possible, but if it is ok according to the MVC way of doing things. (Or should I put the collection of countries in the ViewData inside the controller?)
I would pass the data as a parameter to the GetCountries method. The htmlHelper function really shouldn't know about the properties of your base controller - what if someone were to ever use it on a controller that doesn't inherit from your base? I know I know, you control the code, blah blah. If you're really interested in best practices, avoid the dependency.
public static IEnumerable<SelectListItem> GetCountries(this HtmlHelper html, Countries countries) {
return from c in countries
order by c.Name
select new SelectListItem
{
Text = c.Name,
Value = c.ID
};
}
then, in your View:
<%=Html.GetCountries(this.Entities.Countries)%>
Check out the ViewModel pattern, it's mentioned in the NerdDinner tutorial: http://nerddinnerbook.s3.amazonaws.com/Part6.htm
Basically you create a ViewModel class that encapsulates all the data you might need for your view. So you'd have a class that contains a list of all cities and/or countries, and whatever else, instantiated/populated in the controller action.
Then, you can strongly type your view to use that ViewModel class, and blammo: you've got all the data you need for your form.
I think html helper should return html.
So you have two approaches:
first, if you want to do this as you started, from your htmlhelper prepare your list of elements and then call html.RenderDropDown with initialized list, selected element etc...
second, you can all prepare in your model, so controller will pass initiated object with all elements you need so in you view you can call renderdropdown directly
cheers

Resources