I'd like to take data entered in an MVC user form and display it in a different view.
The class has the following private variable:
IList<string> _pagecontent = new List<string>();
The following action accepts a FormCollection object, validates it, and passes it on to the "Preview" view as a List:
[Authorize(Roles = "Admins")] [ValidateInput(false)] [AcceptVerbs(HttpVerbs.Post)] public ActionResult UpdateContent(FormCollection collection) { if (ModelState.IsValid) { string PageToInsert = collection["PageToInsert"]; string PageHeader = collection["PageHeader"]; string PageBody = collection["PageBody"]; //validate, excluded... _pagecontent.Add(PageToInsert); _pagecontent.Add(PageHeader); _pagecontent.Add(PageBody); } return RedirectToAction("Preview", _pagecontent); }
The Preview view has the following Page Directive for passing a strongly typed object List:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Template.Master" Inherits="System.Web.Mvc.ViewPage<List<string>>" %>
I would expect to be able to use the Model object to get my data, but alas I cannot. At the following line, I get an error index out of bounds
exception, stating the index must be non-negative and less than the size of the collection:
<% if (Model[0].ToString() == "0") { %>
And some strange parameters have been added to the URL, as it resolves to http://localhost:1894/Admin/Preview?Capacity=4&Count=3
So I have two questions:
When a Button is clicked, the Model object is populated with values and passed to the RedirectToAction method along with the name of the Controller and its Action method in ASP.Net MVC Razor.
RedirectToAction(String, Object) Redirects to the specified action using the action name and route values. RedirectToAction(String, String) Redirects to the specified action using the action name and controller name.
To pass multiple values to the new controller method, set TempData values and/or pass them as parameters. First, add keyword/value pairs to the TempData collection to pass any number of values to the view. The temp data collection is persisted across controller method calls.
Try using TempData. It is like a single-shot session object. You put values you want into TempData, immediately redirect and get them out. There is a good writeup here: http://blogs.teamb.com/craigstuntz/2009/01/23/37947/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With