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();
}
Related
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.
I have this api controller action that takes an object "ContentList" as parameter.
[HttpPost]
public List<string> SendList(string param, ContentList list)
{
List<string> testReturn = new List<string> { "test1", "test2", "test3", "test4" };
return testReturn ;
}
What I have tried so far is to call a controller action like this:
Uri _uri = new Uri("http://localhost:xxxxx/api/FakeTest/SendList?param=test");
var serializer = new JavaScriptSerializer();
string requestData = serializer.Serialize(new
{
list = ContentList,
});
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var result = client.UploadData(_uri, Encoding.UTF8.GetBytes(requestData));
var tempString = Encoding.UTF8.GetString(result);
}
In this example, tempString = ["test1","test2","test3","test4"] as reurned by the controller action..
In the controller action, I can access the properties of the passed in ContentList, and return their values (changing the actions return value accordingly ofcourse).
However, in the controller action, I need to send off the ContentList object for further processing, and this seems to fail. I get a 500 internal server error, and I can't put a breakpoint in the controller to follow the values passed in. The debugger never hits it...
I expect this has something to do with sending json to the controller action.
Anyway, it seems that the ContentList is rejected by the code it is sent to from the controller action, so I figure I need to do some sort of de-serializing, right?
Bottomline, the question is, what is the correct way to call a controller action from code, pass in a C# object, and make it usable from the controller action?
If you are using MVC 3 your controller should be able to reveive and parse json data in a direct way. If you are using MVC 2 you'll need to register a new factory on your application to take care of json parsing on the controller
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
More info on the subject here:
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
In the view, for example, in "_Layout.cshtml"
How to get the controller/action which called this view?
After found the controller/action name, then how to get the list of the attribute it has? Or test if it has an attribute?
Thanks.
#ViewContext.Controller will give you the controller instance that returned this view. Once you get the instance, you get the type and once you have the type you get into Reflection to get the attributes this type is decorated with. Writing a custom HTML helper to perform this job could be worth it:
public static class HtmlExtensions
{
public static bool IsDecoratedWithFoo(this HtmlHelper htmlHelper)
{
var controller = htmlHelper.ViewContext.Controller;
return controller
.GetType()
.GetCustomAttributes(typeof(FooAttribute), true)
.Any();
}
}
Since this is the first result in google even when searching for ASP.NET Core version, here's how to do this in .NET Core: Checking for an attribute in an action filter (please upvote original thread)
if (controllerActionDescriptor != null)
{
// Check if the attribute exists on the action method
if (controllerActionDescriptor.MethodInfo?.GetCustomAttributes(inherit: true)?.Any(a => a.GetType().Equals(typeof(CustomAttribute))) ?? false)
return true;
// Check if the attribute exists on the controller
if (controllerActionDescriptor.ControllerTypeInfo?.GetCustomAttributes(typeof(CustomAttribute), true)?.Any() ?? false)
return true;
}
I have the following controller:
class FooController : Controller
{
public ActionResult SomeAction(id)
{
Type t = Type.GetType(id);
object o = Activator.CreateInstance(t);
((MyModel)o).ParseParamaters(PostParameters); // I need to pass the post parameters here
//...
}
}
I would like to fetch all the POST parameters that were submitted.
How can it be done?
You do that with
[HttpPost]
public ActionResult SomeAction(id, FormCollection form)
{
//do what you want with the collection
}
I believe Request.Querystring is just a collection of strings, so you could pass it as a parameter to ParseParameters. Or you could just pass the whole Request object.
But I'm wondering why you'd want to, when there's perfectly good model binding built into MVC to do all the heavy lifting for you. http://weblogs.asp.net/nmarun/archive/2010/02/25/asp-net-mvc-model-binding.aspx
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