I am new to mvc. Exploring the ways to pass value from action method of one controller to other controller. Is this possible to pass xml as value from one controller to other in httppost?
You can use Session, which is available at pretty much any time in a controller, and is very simple to use.
Session["ArbitraryKeyString"] = "Assign any object";
string arbitraryString = (string)(Session["ArbitraryKeyString"] ?? "Session returns null if key not found");
Just be sure to cast it back to the type you need, because it's stored as a Object. You can do this during server calls, since they're all simply external ways to call controller functions, and the values will persist between pages and calls.
Passing it as a parameter is probably your best option. Try using something like return RedirectToAction(ActionName, ControllerName, RouteValues);.
Related
Under ASP.NET MVC are you supposed to pick up QueryString params the same way you do in ASP.NET WebForms? or does the [AcceptVerbs(HttpVerbs.Get)] declaration get used somehow?
Query string parameters can be accepted simply by using an argument on the action - i.e.
public ActionResult Foo(string someValue, int someOtherValue) {...}
which will accept a query like .../someroute?someValue=abc&someOtherValue=123
Other than that, you can look at the request directly for more control.
I think what you are looking for is
Request.QueryString["QueryStringName"]
and you can access it on views by adding #
now look at my example,,, I generated a Url with QueryString
var listURL = '#Url.RouteUrl(new { controller = "Sector", action = "List" , name = Request.QueryString["name"]})';
the listURL value is /Sector/List?name=value'
and when queryString is empty
listURL value is /Sector/List
You can always use Request.QueryString collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.
Actually you can capture Query strings in MVC in two ways.....
public ActionResult CrazyMVC(string knownQuerystring)
{
// This is the known query string captured by the Controller Action Method parameter above
string myKnownQuerystring = knownQuerystring;
// This is what I call the mysterious "unknown" query string
// It is not known because the Controller isn't capturing it
string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];
return Content(myKnownQuerystring + " - " + myUnknownQuerystring);
}
This would capture both query strings...for example:
/CrazyMVC?knownQuerystring=123&unknownQuerystring=456
Output: 123 - 456
Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?
Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.
This is the correct way in .NET 6 (and other netcore)
var Param = Request.Query["IndexString"];
If need to be string
string Param = Request.Query["IndexString"].ToString();
#Context.Request.Query["yourId"]
Under ASP.NET MVC are you supposed to pick up QueryString params the same way you do in ASP.NET WebForms? or does the [AcceptVerbs(HttpVerbs.Get)] declaration get used somehow?
Query string parameters can be accepted simply by using an argument on the action - i.e.
public ActionResult Foo(string someValue, int someOtherValue) {...}
which will accept a query like .../someroute?someValue=abc&someOtherValue=123
Other than that, you can look at the request directly for more control.
I think what you are looking for is
Request.QueryString["QueryStringName"]
and you can access it on views by adding #
now look at my example,,, I generated a Url with QueryString
var listURL = '#Url.RouteUrl(new { controller = "Sector", action = "List" , name = Request.QueryString["name"]})';
the listURL value is /Sector/List?name=value'
and when queryString is empty
listURL value is /Sector/List
You can always use Request.QueryString collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.
Actually you can capture Query strings in MVC in two ways.....
public ActionResult CrazyMVC(string knownQuerystring)
{
// This is the known query string captured by the Controller Action Method parameter above
string myKnownQuerystring = knownQuerystring;
// This is what I call the mysterious "unknown" query string
// It is not known because the Controller isn't capturing it
string myUnknownQuerystring = Request.QueryString["unknownQuerystring"];
return Content(myKnownQuerystring + " - " + myUnknownQuerystring);
}
This would capture both query strings...for example:
/CrazyMVC?knownQuerystring=123&unknownQuerystring=456
Output: 123 - 456
Don't ask me why they designed it that way. Would make more sense if they threw out the whole Controller action system for individual query strings and just returned a captured dynamic list of all strings/encoded file objects for the URL by url-form-encoding so you can easily access them all in one call. Maybe someone here can demonstrate that if its possible?
Makes no sense to me how Controllers capture query strings, but it does mean you have more flexibility to capture query strings than they teach you out of the box. So pick your poison....both work fine.
This is the correct way in .NET 6 (and other netcore)
var Param = Request.Query["IndexString"];
If need to be string
string Param = Request.Query["IndexString"].ToString();
#Context.Request.Query["yourId"]
I have a web page with a search criteria.
Once the user selects what he wants and inputs any keywords to search, he is re-directed to another page which shows the results of his search.
This session object contains all of the information of his search:
var ProjectSearchCriteria = (GBLProjectSearchCriteria) Session[GblConstants.SESSION_PROJECT_SEARCH_CRITERIA];
Is there a way for me to pass this object to an API?
Like so:
[HttpGet]
public List<string> getEpisodes(GBLProjectSearchCriteria psc)
{
var ProjectSearchResult = new ProjectSearchResultController();
var GBLProjectSearchResultListData = ProjectSearchResult.GetProjectSearchResultList(psc);
return (from GBLProjectSearchResult item
in GBLProjectSearchResultListData
select item.Title).ToList();
}
The reason why I want to do this is because the search criteria is massive and it already exists so I don't want the API to have 38032823 parameters.
Is this even possible? How would I do it? Any alternatives?
Web API binds parameters from either URI, query string, etc. or the request body. If you want to bind from any thing else, especially outside of the request message, you can create your own parameter binding. See this. The blog post creates a parameter binding for type IPrincipal but you can do something similar for `GBLProjectSearchCriteria'.
Have you tried?
getEpisodes((GBLProjectSearchCriteria) Session[GblConstants.SESSION_PROJECT_SEARCH_CRITERIA]);
One obvious question I have is, since you know the datatype already, and are type-casting to it, why are you using var?
var ProjectSearchCriteria = (GBLProjectSearchCriteria) ....
Doesn't this make more sense?
GBLProjectSearchCriteria ProjectSearchCriteria = (GBLProjectSearchCriteria) ....
I dont get it, I have this code:
return JavaScript(string.Format(
"window.location = '{0}'",
UrlHelper.GenerateContentUrl("Index", this.HttpContext)));
The code is inside two pretty generic "Create" methods that works with POST. Each of the two methods are in different controller classes.
Now for method A that is called with the URL http://localhost:56688/Businessrule/Create, when the code is executed I get redirected to http://localhost:56688/Index.
But for method B called from http://localhost:56688/FormulaField/Create I get redirected to http://localhost:56688/FormulaField/Index.
... really I don't get it, and the microsoft documentation isn't helping out much http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.generatecontenturl.aspx (now, IMHO, that's a pretty crappy documentation for a method)
Sounds like your missing the controller name. apperently, you're being redirected to the Index action in the same controller.
It's what the MVC Route engine do, if he does not find the controller name, he assign a default value, in this case, the controller from witch the action has been executed.
Try something like :
UrlHelper.GenerateContentUrl(#"~\ControllerName\Index", this.HttpContext)
So, as pointed by asawyer how it works is answered by the code itself:
https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Web.Mvc/UrlHelper.cs
It turns out that if the string that you pass begin with "~" the method will call PathHelpers.GenerateClientUrl, but if the string doesn't begin with "~" it will just return the same string unchanged.
But still I don't undertand why I'm getting different results. Anyway seems that I'll have to look closer to the raw response passed to the browser...
Heading
I want to pass some variables from one page to another but I don't want them to appear in the URL. When I use a form to post the an ActionResult it works fine. However, when I do this
return RedirectToAction("Trackers",new{page = 1, orderby=desc});
I get the URL:
http://examplesite.com/Trackers?page=1&orderby=desc
Is there any way I can get the following URL instead but still pass the page and orderby variables "behind the scenes"?
http://examplesite.com/Trackers
Thanks
TheLorax
I'm not sure it's a good idea to do what you're suggesting, however, you might be able to use the TempData (same place as the ViewData) to save your information before the redirect. I believe that after your next request, anything in the temp data is cleared out.
You could pass a Model object containing the page number and the orderby instead of an anonymous object, and have your view inherit the model class of the object you are passing. Your model object with the page number and orderby then becomes available to the view, without employing a query string
This is not, however, the preferred method of doing this. Your model objects should be reserved for their intended purpose, which is passing actual data to your view.
When you use RedirectToAction method the browser will recieve an http redirect response from the server and then will do a GET request to the new URL.
I think there is no way to make the browser make a POST request when redirecting.
Also it is better to pass these variables through the query string in order for the user to be able to bookmark the page.