Pass Data to MVC Action Method - asp.net-mvc

I need to pass data to the action method below from another action method or another view. Then it will be used where the arrow points. But this action method already has a parameter and get value from its own view. And it mustn't have more than one parameter. I don't know how.

Try to use TempData like below examples:
pass data from action to another action
public ActionResult Action_A()
{
TempData["Data"] = "ABC";
return View();
}
public ActionResult Action_B()
{
var data = TempData["Data"];
return View();
}
pass data from action view to another action
Action View
#{
TempData["Data"] = "hello";
}
<p>This is a Demo</p>
Another Action
public ActionResult Action_B()
{
var data = TempData["Data"];
return View();
}

Related

Difference between View Data,View Bag and Temp Data in mvc [duplicate]

Could any body explain, when to use
TempData
ViewBag
ViewData
I have a requirement, where I need to set a value in a controller one, that controller will redirect to Controller Two and Controller Two will render the View.
I have tried to use ViewBag, the value gets lost by the time I reach Controller Two.
Can I know when to use and advantages or disadvantages?
Thanks
1)TempData
Allows you to store data that will survive for a redirect. Internally it uses the Session as backing store, after the redirect is made the data is automatically evicted. The pattern is the following:
public ActionResult Foo()
{
// store something into the tempdata that will be available during a single redirect
TempData["foo"] = "bar";
// you should always redirect if you store something into TempData to
// a controller action that will consume this data
return RedirectToAction("bar");
}
public ActionResult Bar()
{
var foo = TempData["foo"];
...
}
2)ViewBag, ViewData
Allows you to store data in a controller action that will be used in the corresponding view. This assumes that the action returns a view and doesn't redirect. Lives only during the current request.
The pattern is the following:
public ActionResult Foo()
{
ViewBag.Foo = "bar";
return View();
}
and in the view:
#ViewBag.Foo
or with ViewData:
public ActionResult Foo()
{
ViewData["Foo"] = "bar";
return View();
}
and in the view:
#ViewData["Foo"]
ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3.
This being said, none of those two constructs should ever be used. You should use view models and strongly typed views. So the correct pattern is the following:
View model:
public class MyViewModel
{
public string Foo { get; set; }
}
Action:
public Action Foo()
{
var model = new MyViewModel { Foo = "bar" };
return View(model);
}
Strongly typed view:
#model MyViewModel
#Model.Foo
After this brief introduction let's answer your question:
My requirement is I want to set a value in a controller one, that
controller will redirect to ControllerTwo and Controller2 will render
the View.
public class OneController: Controller
{
public ActionResult Index()
{
TempData["foo"] = "bar";
return RedirectToAction("index", "two");
}
}
public class TwoController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Foo = TempData["foo"] as string
};
return View(model);
}
}
and the corresponding view (~/Views/Two/Index.cshtml):
#model MyViewModel
#Html.DisplayFor(x => x.Foo)
There are drawbacks of using TempData as well: if the user hits F5 on the target page the data will be lost.
Personally I don't use TempData neither. It's because internally it uses Session and I disable session in my applications. I prefer a more RESTful way to achieve this. Which is: in the first controller action that performs the redirect store the object in your data store and user the generated unique id when redirecting. Then on the target action use this id to fetch back the initially stored object:
public class OneController: Controller
{
public ActionResult Index()
{
var id = Repository.SaveData("foo");
return RedirectToAction("index", "two", new { id = id });
}
}
public class TwoController: Controller
{
public ActionResult Index(string id)
{
var model = new MyViewModel
{
Foo = Repository.GetData(id)
};
return View(model);
}
}
The view stays the same.
TempData
Basically it's like a DataReader, once read, data will be lost.
Check this Video
Example
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
String str = TempData["T"]; //Output - T
return View();
}
}
If you pay attention to the above code, RedirectToAction has no impact over the TempData until TempData is read. So, once TempData is read, values will be lost.
How can i keep the TempData after reading?
Check the output in Action Method Test 1 and Test 2
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TempData["T"] = "T";
return RedirectToAction("About");
}
public ActionResult About()
{
return RedirectToAction("Test1");
}
public ActionResult Test1()
{
string Str = Convert.ToString(TempData["T"]);
TempData.Keep(); // Keep TempData
return RedirectToAction("Test2");
}
public ActionResult Test2()
{
string Str = Convert.ToString(TempData["T"]); //OutPut - T
return View();
}
}
If you pay attention to the above code, data is not lost after RedirectToAction as well as after Reading the Data and the reason is, We are using TempData.Keep(). is that
In this way you can make it persist as long as you wish in other controllers also.
ViewBag/ViewData
The Data will persist to the corresponding View
ViewBag, ViewData, TempData and View State in MVC
http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html
ASP.NET MVC offers us three options ViewData, VieBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.
Similarities between ViewBag & ViewData :
Helps to maintain data when you move from controller to view. Used to
pass data from controller to corresponding view. Short life means
value becomes null when redirection occurs. This is because their goal
is to provide a way to communicate between controllers and views. It’s
a communication mechanism within the server call.
Difference between ViewBag & ViewData:
ViewData is a dictionary of objects that is derived from
ViewDataDictionary class and accessible using strings as keys. ViewBag
is a dynamic property that takes advantage of the new dynamic features
in C# 4.0. ViewData requires typecasting for complex data type and
check for null values to avoid error. ViewBag doesn’t require
typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Arun Prakash";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Arun Prakash";
return View();
}
In View, we call like below:
#ViewBag.Name
#ViewData["Name"]
TempData:
Helps to maintain data when you move from one controller to other
controller or from one action to other action. In other words when you
redirect, “Tempdata” helps to maintain data between those redirects.
It internally uses session variables. TempData is meant to be a very
short-lived instance, and you should only use it during the current
and the subsequent requests only
The only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view.
It requires typecasting for complex data type and check for null values to avoid error.
public ActionResult Index()
{
var model = new Review()
{
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
}
public ActionResult About()
{
var model= TempData["ModelName"];
return View(model);
}
void Keep()
Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.
#model MyProject.Models.EmpModel;
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep(); // retains all strings values
}
void Keep(string key)
Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.
#model MyProject.Models.EmpModel;
#{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep("emp"); // retains only "emp" string values
}
TempData
will be always available until first read, once you read it its not available any more can be useful to pass quick message also to view that will be gone after first read.
ViewBag
Its more useful when passing quickly piece of data to the view, normally you should pass all data to the view through model , but there is cases when you model coming direct from class that is map into database like entity framework
in that case you don't what to change you model to pass a new piece of data, you can stick that into the viewbag
ViewData is just indexed version of ViewBag and was used before MVC3
Also the scope is different between viewbag and temptdata. viewbag is based on first view (not shared between action methods) but temptdata can be shared between an action method and just one another.

How to add success message after HttpPost submits database changes

I have an HttpPost method that add to the database
public ActionResult SubmitData(MyViewModel model)
{
if (ModelState.IsValid)
{
var result = submitData(command);
if (response.success)
{
return RedirectToAction("MyHttpGetMethod");
}
}
return View("MyHttpGetMethod", model);
}
public ActionResult MyHttpGetMethod(int Id)
{
MyModel model = GetData(Id);
return View(model);
}
After the HttpPost is called and the database changes are made successfully, I redirect to
the HttpGet action to get the current data after the changes. I like to display a success message
on the View. I can't use ViewBag because of the Redirect and I can't use TempData, because it's not recommended here.
TempData is a valid solution for this specific use case. But if you do not prefer to do that, you can pass a querystring value to indicate the status of the transaction from your HttpPost action to the GET action.
So update your GET action to have another paramter
public ActionResult MyHttpGetMethod(int Id,string m="")
{
MyModel model = GetData(Id);
if(!String.IsNullOrEmpty(m) && m=="s")
{
// do some code to show the success message here.
ViewBag.Msg="Saved Successfully";
}
return View(model);
}
and in your view, use the ViewBag item to show the message (with whatever styles you want)
<p>#ViewBag.Msg</p>
and in your HttpPost action,
return RedirectToAction("MyHttpGetMethod", new { id =model.Id, m="s"} );

Mvc Passing data "RedirectToAction" without using Temp data

How to pass model data while redirecting to another action without using TemptData, as given in the example.
Is there an alternate way to pass EmployeeViewModel from "AddEmployee" action to "Preview" action without using TempData/ Session?
public ActionResult AddEmployee(EmployeeViewModel employeeViewModel)
{
TempData["employee"] = employeeViewModel;
return this.RedirectToAction("Preview");
}
public ActionResult Preview()
{
var model = TempData["employee"] as EmployeeViewModel;
return this.View("Preview", employeeViewModel);
}
check this
return RedirectToAction("Index", new { exception = EmployeeViewModel});

MVC any action returns partial view of the same name

I have a controller where all of the action methods contain the same code:
[ActionName("pretty-url")]
public ActionResult Something() {
return PartialView();
}
[ActionName("another-pretty-url")]
public ActionResult SomethingElse() {
return PartialView();
}
I name my partial views in the pretty-url.cshtml format, and these get picked up fine and everything works.
As every action in the controller will always do exactly the same thing and return the same thing, I would like to just have my controller look for the correctly-named view and return it as above, without me having to explicitly implement it.
How would I do that?
TIA
I would create a single action and pass the view name as parameter.
public ActionResult Something(string viewName)
{
return PartialView(viewName);
}
I would add a new method to my controller with a string parameter and use it to load the correct partial view.
public ActionResult Show(string PartialName)
{
return PartialView(PartialName);
}
Now instead of using http://your.domain/pretty_url you will have to use http://your.domain/show/pretty_url but this will work with any new partial view you add later on.

ASP.net MVC4 Clear Model Values

So I have a simple action in my controller. The project is a MVC Mobile Application.
public ActionResult Index()
{
return View();
}
this gives an form to enter data. I then handle the data in the post back.
[HttpPost]
public ActionResult Index(ScanViewModel model)
{
if (ModelState.IsValid)
{
Scan ns = new Scan();
ns.Location = model.Location;
ns.Quantity = model.Quantity;
ns.ScanCode = model.ScanCode;
ns.Scanner = User.Identity.Name;
ns.ScanTime = DateTime.Now;
_db.Scans.Add(ns);
_db.SaveChanges();
}
return View(model);
}
I want to clear the fields in the form and allow users to enter data again. However I get the exact same values back into my inputs. How can I clear them in the controller.
Just call this.ModelState.Clear()
You should follow the PRG pattern.
Just redirect to the Action method which is meant for the Create Screen. You can use the RedirectToAction method to do so.
RedirectToAction returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.
[HttpPost]
public ActionResult Index(ScanViewModel model)
{
if(ModelState.IsValid)
{
//Code for save here
//..............
_db.SaveChanges();
return RedirectToAction("Index","User");
}
return View(model);
}
public ActionResult Index()
{
return View();
}
Assuming your controller name is UserController.

Resources