Pass data from controller to controller withour parameter mvc - asp.net-mvc

I have a controller and I want to send a data to another controllers method. But receiver controller's action method currently in use and I dont want to change its parameter
Just simply want a value that I sent from other controller ?
is it possible with ViewBag ?
I just want something like
Controller1: {...
ViewBag.Data = 10;
...}
Controller2:{...
if(ViewBag.Data !=null)
value = ViewBag.Data
...}

If you wish to pass data from one controller to another and wish to discard the object once it reaches the other controller, you should use TempData.
Controller 1:
public ActionResult Index()
{
TempData["data"] = 10; // somedata;
return RedirectToAction("/Controller2/Index");
}
Contoller 2:
public ActionResult Index()
{
if(TempData["data"] != null)
int i = (int)(TempData["data"]) // Perform unboxing
}

Related

passing value in partial view viewdatadictionary

#Html.Partial("~/Areas/WO/Views/PartialContent/_FirstPage.cshtml", new ViewDataDictionary { { "WOID", WOID } })
In my Page i am accessing Partial view in the above way.
I need to pass WOID(view data dictionary) value from query string, For that i am using following Code
#{
var desc = Html.ViewContext.HttpContext.Request.QueryString.Get("ID");
Uri referrer = HttpContext.Current.Request.UrlReferrer;
string[] query = referrer.Query.Split('=');
int WOID = Convert.ToInt32(query[1]);
}
But the issue is this code is working in all browsers except I.E. i Need to Solve this problem.
Please help me
Instead of this you can have this value as part of you model and use that.That is the standard and recommeded way .
In your action method you can have these as parameter.Your query string value will get bind to this parameter
public ActionResult ActionMethod(int ID)
{
Model.WOID = WOID;
// Other logic
return View(Model)
}
Next step you can add this as a property to your view model or add it to ViewData dictionary and then access it in your partial view.

Controller searching for view instead of returning a different view method

I have two controller actions outlined below:
public ViewResult TitleStorylines(int id)
{
var vm = Service.Get(id);
vm.IsEditable = User.HasPermission(SecurityPermissionType.ManageStorylines);
return View(vm);
}
public ViewResult TitleStorylinesCreate(TitleStorylineModel model)
{
var created = Service.Create(model);
return TitleStorylines(created.TitleId);
}
I only have one view in my project, called TitleStorylines, which the first controller action handles fine. But when I call the second method, it gives me an error saying that it can't find the view called TitleStorylinesCreate even though I'm explicitly calling the previous method. What gives?
Did you try ?
return View("TitleStorylines",created.TitleId);
EDIT: Based on your update : I guess you are posting your form back the TitleStorylinesCreate. So probably after saving, dont you want to redirect the user back to the Get action of same ?
[HttpPost]
public ViewResult TitleStorylinesCreate(TitleStorylineModel model)
{
var created = Service.Create(model);
return RedirectToAction("TitleStorylines",new { #id=created.TitleId});
}
In the above example we are doing the PRG pattern. Post -> Redirect -> Get
After saving, we are redirecting them back to the first method. It will be a HTTP GET method.
public ActionResult TitleStorylinesCreate(TitleStorylineModel model)
{
var created = Service.Create(model);
return RedirectToAction("TitleStorylines",new { #id=created.TitleId});
}

Persist values between two action results in one controller

I am generating values in one action method of a controller. How can I use the same variables values in another action result from the same controller?
For example:
Controller A - Action result 1 :
public ActionResult CalculationsONE()
{
dynamic CalcModel = new ExpandoObject();
int var1 = //Value calculated here
int var2 = //Calculation
CalcModel.Var1= var1;
CalcModel.Var2= var2;
return View(CalcModel);
}
Controller A - Action result 2:
public ActionResult CalculationsTWO()
{
// I want to use var1 and var2 from the CalculationsONE in
this action result
}
Simply pass them as query string parameters:
public ActionResult CalculationsTWO(int var1, int var2)
{
...
}
and in order to invoke the CalculationsTWO action from within the view rendered in CalculationsONE action you could generate a link like this:
#model CalcModel
#Html.ActionLink(
"call calculations2",
"calculationstwo",
"somecontroller"
new {
var1 = Model.Var1,
var2 = Model.Var2
}
)
Oh, and I would recommend you using strongly typed view models instead of dynamic objects passed to the view. ViewBag is dynamic but honestly, use view models. You will be happier :-)
If they are two separate actions the above answer from Darin Dimitrov should do it otherwise if you want both results in one resource call create two private methods in your controller that do calc1 and calc2 and return the results to the view...
results: {
calc1: ....
calc2: ....
}
you can use class vars like you currently are to keep track of the values.
As alternative I would go about it in way of saving your variables into session.
EG:
this.Session["variable"]
this.HttpContext.Session["variable"]
or pass them via ViewData["string"] into view and in Controller on Request.FormData["VariableName"] to bind it back
another way is
add the data to model for the view
and on postback in your controller bind the model back into variable
eg:
// postback action
public ActionResult RebindMethod(ModelToUse rebindToMyModel){
}
Where Model definition is:
public class ModelToUse{
public string MyVariableToPersist{get;set;}
}

redirectToAction results in null model

I have 2 actions on a controller:
public class CalculatorsController : Controller
{
//
// GET: /Calculators/
public ActionResult Index()
{
return RedirectToAction("Accounting");
}
public ActionResult Accounting()
{
var combatants = Models.Persistence.InMemoryCombatantPersistence.GetCombatants();
Debug.Assert(combatants != null);
var bvm = new BalanceViewModel(combatants);
Debug.Assert(bvm!=null);
Debug.Assert(bvm.Combatants != null);
return View(bvm);
}
}
When the Index method is called, I get a null model coming out. When the Accounting method is called directly via it's url, I get a hydrated model.
This is less an answer than a workaround. I am not sure why you are getting a null model as it looks like it should work. In fact, I can confirm the behavior you are seeing when I try it out myself. [EDIT: I discovered a flaw in my initial test code that was causing my own null model. Now that that is corrected, my test works fine using RedirectToAction.] If there is a reason for it, I don't know it off the top of my head.
Now for the workaround...I assume that you are doing it this way since the default route sends all traffic to http://www.domain.com/Calculators to "Index". So why not create a new route like this:
routes.MapRoute(
"Accounting",
"Calculators/{action}/",
new { controller = "Calculators", action = "Accounting" }
);
This route specifies the default action to the Calculators controller will be "Accounting" instead of Index.
Your view for the Action Accounting expects a model. (the BalanceViewModel). The index action method does not have a instance of the BalanceViewModel.
There are a number of ways you can solve this. In your View (aspx page) you can check for nulls...
Or in the index action method, you create a new instance of a BalanceViewModel and store it in TempData, and then retrieve this in your view when your model is null.
Or in your action method, you could also call return View("Accounting", new BalanceViewModel()) instead of using redirect to action.
EDIT: Example Code -
If you want to share this functinality, create a private method like this:
public class CalculatorsController : Controller {
// GET: /Calculators/
public ActionResult Index() {
return View(GetBalanceViewModel());
}
public ActionResult Accounting() {
return View(GetBalanceViewModel());
}
private BalanceViewModel GetBalanceViewModel() {
var combatants = Models.Persistence.InMemoryCombatantPersistence.GetCombatants();
Debug.Assert(combatants != null);
var bvm = new BalanceViewModel(combatants);
Debug.Assert(bvm != null);
Debug.Assert(bvm.Combatants != null);
return bvm;
}
}
Have you seen this Question?

Can't pass viewmodel to new action by RedirectToAction

I have a form, when user submit the form, I want to direct the user the new view to display the submitted result(transfer viewmode data to display view).
public class HomeController : Controller
{
private MyViewModel _vm;
.....
// POST: /Home/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyViewModel vm){
//.....
//set up vm to temp data _vm
_vm = vm;
return RedirectToAction("DisplayData");
}
// GET: /Home/DisplayData
public ActionResult DisplayData()
{
//get temp data for display
return View(_vm);
}
}
When I posted the form, I can create vm and put it to temp data place _vm. But this _vm can be sent to another action DisplayData, it's null in action DisplayData(). It seems that when redirect action even in same controller, _vm is lost although it is Controller var, not action method var.
How to resolve this problem?
It creates a new instance of the controller as it is a new request therefore as you have found it will be null.
You could use TempData to store the vm, TempData persists the data for 1 request only
Good explanation here
One good way is to call
return DisplayData(_vm)
instead of
RedirectToAction("DisplayData")
DisplayData should accept a model anyway.

Resources