Redirect IGrouping<string, model> List to another action in Same Controller - asp.net-mvc

return RedirectToAction("ActionName", new { lst = finalData });
[HttpGet]
Public ActionResult AcionName(IGrouping<string, ModelName> lst)
{
return View("ActionName", lst);
}
i use this code to redirect my list to another action but this is not working.

You can assign the finalData to a Session or TempData variable.
TempData["FinalData "] = finalData;
return RedirectToAction("ActionName");
From this answer: "TempData Allows you to store data that will survive for a redirect. Internally it uses the Session, it's just that after the redirect is made the data is automatically evicted"
Then in your GET Action Method,
Public ActionResult AcionName()
{
var finalData = TempData["FinalData"] as IGrouping<string, ModelName>;
return View("ActionName", finalData);
}
The problem is, if you were to refresh after the redirect, then finalData would be null. So, in that case you use Session["FinalData"] or get the data from the Database in your Get method again. You can go through the answer I have linked for disadvantages of using TempData.

Related

Redirect page in c# mvc

I have link
http://localhost:3163/PaymentOrder?AgentCode=&InvoiceNo=&AgentName=&FromDate=&fromDate=12%2F11%2F2013&FromDate=12%2F11%2F2013+9%3A08%3A01+SA&toDate=12%2F11%2F2013
after click button "Delete" the page should be redirect to "Index"
return RedirectToAction("Index","PaymentOrder");
But i want keep link same as first, i don't know what method, please help me. thanks
I can fix it, i save session in
public ActionResult Index{
Session["LastPage"] = Request.Url.ToString();
}
after I'm
return Redirect(Session["LastPage"] as String);
You can pass the query strings to the third parameter of RedirecToAction
return RedirectToAction("Index","PaymentOrder", new { fromDate = model.FromDate });
Or pass the entire model as well, that contains the properties similar to your query strings
return RedirectToAction("Index","PaymentOrder", new { paymentModel = model });
As your query string is quite long, it would probably be better to write an extension method and use that instead, to keep your controllers thin. I haven't tested this, but something like this should work:
public static RouteValueDictionary ToRouteDictionary(this NameValueCollection nameValues)
{
if (nameValues == null || nameValues.HasKeys() == false)
return new RouteValueDictionary();
var routeValues = new RouteValueDictionary();
foreach (var key in nameValues.AllKeys)
routeValues.Add(key, nameValues[key]);
return routeValues;
}
Then in your controller:
return RedirectToAction("Index","PaymentOrder", Request.QueryString.ToRouteDictionary());
Just don't redirect but return the view, the URL will remain the same.

Pass information back to the view when using Redirect()

I am calling a controller from more than one page and am using a returnUrl parameter to return the correct calling location:
public ActionResult EmailOrder(int id, string returnUrl)
{
var message = "The order has been emailed";
if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
return RedirectToAction("Details", new { id, message });
}
How can I pass additional information back to the view when using Redirect(url)? In the above example, I want to be able to pass message back when returnUrl has a value.
If you are redirecting to another action method and you want to pass data that can be access in the new action method, you should use the ASP.MVC Controller TempData property. You use this as follows:
[HttpPost]
public ActionResult MyActionMethod(Order order)
{
// write your logic here to save the Order
TempData["message"] = "here is some message";
return RedirectToAction("Index");
}
Data in the TempData member will be preserved across a redirection. It will be accessible in the redirected page, and then will be removed. Once you read an entry in TempData, it will be marked for deletion.
public ActionResult RedirectedMethod()
{
//Retrieve data from TempData. It will then be marked for deletion
var data = TempData["message"].ToString();
}
If you want to get a value without marking it for deletion, you can use the "Peek" method:
var data = TempData.Peek("message")
Also, you can manually preserve a value that would otherwise be deleted by using the "Keep" method:
TempData.Keep("message")
TempData is of type TempDataDictionary.
Note that TempData uses ASP.Net Session state behind the scenes, so you must have session state turned on if you are using TempData.
For more information on TempData, see here.

How do I include a model with a RedirectToAction?

In the RedirectToAction below, I'd like to pass a viewmodel. How do I pass the model to the redirect?
I set a breakpoint to check the values of model to verify the model is created correctly. It is correct but the resulting view does not contain the values found in the model properties.
//
// model created up here...
//
return RedirectToAction("actionName", "controllerName", model);
ASP.NET MVC 4 RC
RedirectToAction returns a 302 response to the client browser and thus the browser will make a new GET request to the url in the location header value of the response came to the browser.
If you are trying to pass a simple lean-flat view model to the second action method, you can use this overload of the RedirectToAction method.
protected internal RedirectToRouteResult RedirectToAction(
string actionName,
string controllerName,
object routeValues
)
The RedirectToAction will convert the object passed(routeValues) to a query string and append that to the url(generated from the first 2 parameters we passed) and will embed the resulting url in the location header of the response.
Let's assume your view model is like this
public class StoreVm
{
public int StoreId { get; set; }
public string Name { get; set; }
public string Code { set; get; }
}
And you in your first action method, you can pass an object of this to the RedirectToAction method like this
var m = new Store { StoreId =101, Name = "Kroger", Code = "KRO"};
return RedirectToAction("Details","Store", m);
This code will send a 302 response to the browser with location header value as
Store/Details?StoreId=101&Name=Kroger&Code=KRO
Assuming your Details action method's parameter is of type StoreVm, the querystring param values will be properly mapped to the properties of the parameter.
public ActionResult Details(StoreVm model)
{
// model.Name & model.Id will have values mapped from the request querystring
// to do : Return something.
}
The above will work for passing small flat-lean view model. But if you want to pass a complex object, you should try to follow the PRG pattern.
PRG Pattern
PRG stands for POST - REDIRECT - GET. With this approach, you will issue a redirect response with a unique id in the querystring, using which the second GET action method can query the resource again and return something to the view.
int newStoreId=101;
return RedirectToAction("Details", "Store", new { storeId=newStoreId} );
This will create the url Store/Details?storeId=101
and in your Details GET action, using the storeId passed in, you will get/build the StoreVm object from somewhere (from a service or querying the database etc)
public ActionResult Details(string storeId)
{
// from the storeId value, get the entity/object/resource
var store = yourRepo.GetStore(storeId);
if(store!=null)
{
// Map the the view model
var storeVm = new StoreVm { Id=storeId, Name=store.Name,Code=store.Code};
return View(storeVm);
}
return View("StoreNotFound"); // view to render when we get invalid store id
}
TempData
Following the PRG pattern is a better solution to handle this use case. But if you don't want to do that and really want to pass some complex data across Stateless HTTP requests, you may use some temporary storage mechanism like TempData
TempData["NewCustomer"] = model;
return RedirectToAction("Index", "Users");
And read it in your GET Action method again.
public ActionResult Index()
{
var model=TempData["NewCustomer"] as Customer
return View(model);
}
TempData uses Session object behind the scene to store the data. But once the data is read the data is terminated.
Rachel has written a nice blog post explaining when to use TempData /ViewData. Worth to read.
Using TempData to pass model data to a redirect request in Asp.Net Core
In Asp.Net core, you cannot pass complex types in TempData. You can pass simple types like string, int, Guid etc.
If you absolutely want to pass a complex type object via TempData, you have 2 options.
1) Serialize your object to a string and pass that.
Here is a sample using Json.NET to serialize the object to a string
var s = Newtonsoft.Json.JsonConvert.SerializeObject(createUserVm);
TempData["newuser"] = s;
return RedirectToAction("Index", "Users");
Now in your Index action method, read this value from the TempData and deserialize it to your CreateUserViewModel class object.
public IActionResult Index()
{
if (TempData["newuser"] is string s)
{
var newUser = JsonConvert.DeserializeObject<CreateUserViewModel>(s);
// use newUser object now as needed
}
// to do : return something
}
2) Set a dictionary of simple types to TempData
var d = new Dictionary<string, string>
{
["FullName"] = rvm.FullName,
["Email"] = rvm.Email;
};
TempData["MyModelDict"] = d;
return RedirectToAction("Index", "Users");
and read it later
public IActionResult Index()
{
if (TempData["MyModelDict"] is Dictionary<string,string> dict)
{
var name = dict["Name"];
var email = dict["Email"];
}
// to do : return something
}
Another way to do it is to store it in the session.
var s = JsonConvert.SerializeObject(myView);
HttpContext.Session.SetString("myView", s);
and to get it back
string s = HttpContext.Session.GetString("myView");
myView = JsonConvert.DeserializeObject<MyView>(s);

Passing ArrayList parameter to controller action ASP.NET MVC

I am writing an application wherein I need to send a System.Collections.ArrayList data as a parameter from one controller action to another.
I am using
return RedirectToAction("action1","controller1", new { arrList = arrListInFirstAction});
But since the ArrayList goes out of scope in the first action, the parameter in the redirected to action receives a null parameter.
Can someone please help me find an answer to this problem.
Thanks.
you can not send complex types as route parameters. you can, however, use TempData collection to keep that object for one request and on next request it will be automatically removed from collection
publci ActionResutl action()
{
TempData["arr"] = new int[]{1,2,3};
return RedirectToAction("action1");
}
Public ActionResult action1()
{
int[] arr = TempData["arr"];
return View();
}

How to pass thw Viewdata to all the views in my controller?

i have a dropdown list which select a value
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Screenname(FormCollection collection)
{
Viewdata["screenname"] = collection[0];
return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
}
then i want to access this ViewData in other actions like this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection, string screenname)
{
try
{
/// thats my dataobject which creates
DataObj.SaveData(Guid.Empty, collection, screenname);
return RedirectToAction("Index", new { ScreenName = ViewData["screenname"] });
}
catch
{
return View("Error");
}
}
where index looks like this ...
public ActionResult Index(string ScreenName)
{
///thats my list
GetTable = new GetDataTable(ScreenName);
return View(GetTable);
}
First when i select the value and index gets executed properly.... but when i try to access the viewdata again it doesn't contain the value so anybody if please can help ...
or alternate method to save and retrieve data .
The ViewData object is specific for the particular action that is executing. To pass data between actions, use TempData. more on the difference between the two on MSDN.
You can also directly write to the session state through the Controller.Session property.
This has actually been covered quite often here. The solution for now is to use TempData to save the data you need before you use RedirectToAction().
If you do a search for "RedirectToAction" you'll find a number of posts covering this topic, such as this one.
The next official release of the framework will fix this.
I used a view to take the data from the user and then saved it to a static variable and then used this variable to pass the data to all the other views .
Thanks anyways

Resources