How to pass information to Asp.Net MVC partial view? - asp.net-mvc

In Asp.Net MVC, the Account controller's Login method, if successful, returns RedirectToLocal(returnUrl);
I want to add a string to return. I thought ViewBag or TempData would do, but the View finds those to be empty. So I guess those don't get passed to the View, even though that's their exact purpose, from what I read.
There's got to be an easy way...other than returning to Classic ASP.

It sounds like you want to declare (optional?) parameters on the route you're redirecting to.
For example, something like:
return RedirectToAction("Action", new { id = 99 });
Here are a few links that might help:
MVC RedirectToAction passing route parameters
Passing data from one controller to another in ASP.NET MVC
PS:
Please don't return to "Classic ASP.Net" (or "even-more-classic ASP 3.0" ;)). Get familiar with MVC, and look forward to ASP.Net Core (which is MVC from the ground up ;))

Related

Asp.net MVC redirect Url to another controller view

I am very new to MVC and trying to migrate asp.net application to MVC. Basically I am trying to reuse the code where ever possible. In one case I was trying to use Redirect("SomeUrl") and it works pretty well with the view under same controller.
For eg., I added below piece of code in HomeController.cs
public ActionResult Login()
{
return Redirect("HomeMgr?Section=home&Type=Mgr");
}
Well, could someone suggest me if I can use Redirect(Url) to redirect to a view in another Controller? is there any format for Url something like
"~/controllername/Viewname?something=something&something=otherthing"
(I've read in other posts that I can achieve this using RedirectToAction, but I am trying not to change existing code which uses querystring values. )
Don't use Redirect to redirect to Actions in your app. There are several reasons for this. First, it's just simpler to user RedirectToAction as Alundra's answer provides. However, simpler is only part of the answer.
There's a problem with using Redirect. And that has to do with the way Routing works in MVC. In MVC, you can reach the same action via multiple different URL's. For instance, in a default MVC template, the following are all valid URL's.
http://yoursite/
http://yoursite/Home
http://yoursite/Home/Index
Now, what happens when you use Redirect? If you use the last url, it will work fine. You'll end up with the following url.
http://yoursite/Home/HomeMgr?Section=home&Type=Mgr
But if you're at any of the others, you have a problem...
http://yoursite/HomeMgr?Section=home&Type=Mgr
Oops... that won't work... That will be looking for a controller named HomeMgrController.
You get the same at the root as well.
Using RedirectToAction solves this problem, as it takes your routing into account and will figure out the correct url to redirect you to based on the Controller and Action you specify.
return RedirectToAction("ActionName", "ControllerName", new { Section=home,Type=Mgr ......Anythingelse you want to pass });

ASP MVC WebGrid pagination link generation

ASP MVC WebGrid renders pagination links like
http://host/AnyController/AnyAction?Length=4&page=1
Any chance to parametrize or customize this to
http://host/AnyController/AnyAction/1
to conform better to MVC routing conventions?
(NOT important: btw Length is redundant. If the controller's Action method does not know the page length, by heart that's problem. )
Thanks in advance
One way to handle your default route conflict can be this, as most of the time when you use you route it will hit the action method without the [HttpGet]. All you need to do is a GET, whenever you sort or page the web gird, it will try to get data and hit the a HttpGet Action, this will work as follows:
[HttpGet]
public ActionResult YourActionMethod()
{
return PartialView("YourView",YourModel);
}
The best part is, upon sorting, the request will send a parameter named as "sortBy" too, you can use this here and decide what you want to do with the binded Model with the grid. You can inspect what URL the Sort header will hit by using the "Developer Tools" in your browser. You can use this action do as you will,
Note : By default the action method it would be hitting would be same as the controller name.

Passing empty model back to create view after successful add - textboxes still contain data?

ASP.NET MVC 4 web app, SQL Server 2012, Entity Framework 5.
I have a view, based on scaffolding - after successfully creating a record in the database rather than calling
return RedirectToAction("Index");
I want users to be able to immediately add another record. However if I instead return an empty model - eg like this:
return View(new Tag());
The textboxes still have the old model data in. Shouldn't they be cleared?
What I want to do is clear all textboxes so the user can enter the next item.
Your problem is in ModelState. It contains values that was posted and fill them on client. You can clear it with ModelState.Clear() if i remember this. But it is not so good solution. Good solution redirect to right action instead of returning View(new Tag())
I found the answer here:
ASP.net MVC4 Clear Model Values
You need to call the Http Get Action on the Create Action Method - like this:
return RedirectToAction("Create", "ControllerName");
This appears to reset the model, using the PRG pattern. Still not totally sure why it didn't work the first time but this makes sense as a better approach.

Sending a parameter to the controller in ASP MVC 2

I am writing an area for administering several subsites, almost all of the functionality will be the same across each site (add/edit/remove pages etc) and my repository on instantiation takes the SiteIdentity so all the data access methods are agnostic in relation to this. The problem I have at the moment is trying to make my action methods also agnostic.
The URL pattern I want to use is along the lines of:
"ExternalSite/{identity}/{controller}/{action}/{id}"
A naive approach is to have each action take the identity parameter, but this means having to pass this in to my repository on each action as well as include it in the ViewData for a couple of UI elements. I'd much rather have this something that happens once in the controller, such as in its constructor.
What is the best way to do this? Currently the best I can come up with is trying to find and cast identity from the RouteData dictionary but part of me feels like there should be a more elegant solution.
It sounds like you want to use OnActionExecuting or a Custom ModelBinder to do that logic each time you have a specific parameter name (also known as a RouteData dictionary key).
Creating a custom modelbinder in ASP.NET MVC
Creating an OnActionExecuting method in ASP.NET MVC, Doing Serverside tracking in ASP.NET MVC
You have access to your route values in Request.RequestContext.RouteData, so you can make base controller and public property SiteIdentity, in such case you can access it from all actions in all inherited controllers.

Validating posted form data in the ASP.NET MVC framework

I've been playing around with the ASP.NET MVC Framework and the one thing that's really confusing me is how I'm meant to do server side validation of posted form data. I presume I don't post back to the same URL, but if I don't, how do I redisplay the form with the entered data and error messages? Also, where should the validation logic go? In the model or the controller? This seems to be one of the few areas where web forms are much stronger (I miss the validation controls).
Here's an overview of the flow in MVC:
/new - render your "New" view containing a form for the user to fill out
User fills out form and it is posted to /create
The post is routed to the Create action on your controller
In your action method, update the model with the data that was posted.
Your Model should validate itself.
Your Controller should read if the model is valid.
If the Model is valid, save it to your db. Redirect to /show to render the show View for your object.
If the Model is invalid, save the form values and error messages in the TempData, and redirect to the New action again. Fill your form fields with the data from TempData and show the error message(s).
The validation frameworks will help you along in this process. Also, I think the ASP.NET MVC team is planning a validation framework for the next preview.
You might want to take a look at ScottGu's latest post for ASP.Net prev 5. It walks through a validation sample that is very interesting:
http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx
As far as I can tell everyone is still trying to figure out the "standard" way of doing it. That said definitely check out Phil Haack and Scott Guthrie's latest posts on MVC and you'll find some interesting info on how they did. When I was just playing around with it for myself I created a ModelBinder for the LinqToSql data class that I had generated. You can check out this post to find out how to put together a basic ModelBinder:
ASP.Net MVC Model Binder
The in your action if you had created a "Product" ModelBinder you would just declare the action like so:
public ActionResult New(Product prod)
And the model binder will take care of assigning posted data to the objects properties as long as you've built it right anyway.
After that within your GetValue() method you can implement whatever validation you want, whether using exception's, regex's, or whatever you can make a call like:
(ModelStateDictionary_name).AddModelError("form_element_id", "entered_value", "error_message");
Then you can just throw a <%= Html.ValidationSummary() %> in your view to display all your errors.
For client-side validation I just used jQuery. After you get a basic sample set up though you can start doing some interesting things combining all that with Partial Views and Ajax calls.
Have you taken a look at this?
http://www.codeplex.com/MvcValidatorToolkit
Quoted from the page
The Validator Toolkit provides a set
of validators for the new ASP.NET MVC
framework to validate HTML forms on
the client and server-side using
validation sets.
I'm afraid that someone more MVC-savvy than me would have to speak to where in the architecture you should put things.
I'm just learning the MVC framework too so I'm not sure how off this is, but from what I understand you would have a form on a View such as Edit.aspx. This form would then post to the controller to another action method such as Update() passing in the contents of the form that you set in Edit.aspx as parameters.
Update(int id, string name, string foo)
You could do the validation within that method. If all is ok,
return View("Item", yourObject)
There is Castle.Components.Validator module in Castle project. It's very agile and powerfull. It generates validation rules based on model attributes (or any other source) and even able to generate JS validation using jQuery, Prototype Validation, fValidate and other.
Of course it's wise to abstract validator away behind IValidationEngine interface.

Resources