Persist values between two action results in one controller - asp.net-mvc

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;}
}

Related

How can I send a parameter to partial view without the need of a model?

I have a partial view in my MVC app which I load into a container dom element. I do this by first calling the controller, like so:
$(container).load('/xxx/GetPartialView');
In the controller I return the partial view:
public PartialViewResult GetPartialView()
{
return PartialView("SomePartial", null);
}
This works just fine. However, I would like to send a parameter (just a simple string value) along from the controller to the partial view I'm creating. This I understand, can be done by the use of a model, like for example:
public PartialViewResult GetPartialView(string someValue)
{
return PartialView("SomePartial", new SomeDummyModel(someValue));
}
But I would like to avoid the model instance if possible, as it seems like a lot of overhead. I want to just send the string value as a parameter. Is that possible?
Instead of passing a custom class such as SomeDummyModel you can simply pass someValue. Assuming that someValue is string from your explanation, that would mean you would accept string in the #model of your partialView.
controller
public PartialViewResult GetPartialView(string someValue)
{
return PartialView("SomePartial", someValue);
}
partial
#model string
<div>Hello, #Model :)</div>
You can also use the ViewData object to pass simple items like that.
public PartialViewResult GetPartialView()
{
ViewData["someValue"] = "hello";
return PartialView("SomePartial", null);
}
And then in the view access it:
<div>#ViewData["someValue"].ToString() :)</div>
This works without a model.
You can put pretty much anything into the ViewData object, you just need to cast it out

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.

Pass data from controller to controller withour parameter 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
}

MVC - one controller action with multiple model types/views or individual controller actions?

In my project I have a controller that allows you to create multiple letters of different types. All of these letter types are stored in the database, but each letter type has different required fields and different views.
Right now I have a route set up for the following URL: /Letters/Create/{LetterType}. I currently have this mapped to the following controller action:
public ActionResult Create(string LetterType)
{
var model = new SpecificLetterModel();
return View(model);
}
I also have a View called Create.cshtml and an EditorTemplate for my specific letter type. This all works fine right now because I have only implemented one Letter Type. Now I need to go ahead and add the rest but the way I have my action set up it is tied to the specific letter type that I implemented.
Since each Letter has its own model, its own set of validations, and its own view, what is the best way to implement these actions? Since adding new letter types requires coding for the model/validations and creating a view, does it make more sense to have individual controller actions:
public ActionResult CreateABC(ABCLetterModel model);
public ActionResult CreateXYZ(XYZLetterModel model);
Or is there a way I can have a single controller action and easily return the correct model/view?
You can do one of the following:
Have a different action method for each input. This is because the mvc framework will see the input of the action method, and use the default model binder to easily bind the properties of that type. You could then have a common private method that will do the processing, and return the view.
Assuming XYZLetterModel and ABCLetterModel are subclasses of some base model, your controller code could look like:
public class SomeController : Controller
{
private ISomeService _SomeService;
public SomeController(ISomeService someService)
{
_SomeService = someService;
}
public ViewResult CreateABC(ABCLetterModel abcLetterModel)
{
// this action method exists to allow data binding to figure out the model type easily
return PostToServiceAndReturnView(abcLetterModel);
}
public ViewResult CreateXYZ(XYZLetterModel xyzLetterModel)
{
// this action method exists to allow data binding to figure out the model type easily
return PostToServiceAndReturnView(xyzLetterModel);
}
private ViewResult PostToServiceAndReturnView(BaseLetterModel model)
{
if (ModelState.IsValid)
{
// do conversion here to service input
ServiceInput serviceInput = ToServiceInput(model);
_SomeService.Create(serviceInput);
return View("Success");
}
else
{
return View("Create", model);
}
}
}
The View code could look like:
#model BaseLetterModel
#if (Model is ABCLetterModel)
{
using (Html.BeginForm("CreateABC", "Some"))
{
#Html.EditorForModel("ABCLetter")
}
}
else if (Model is XYZLetterModel)
{
using (Html.BeginForm("CreateXYZ", "Some"))
{
#Html.EditorForModel("XYZLetter")
}
}
You would still have an editor template for each model type.
Another option is to have a custom model binder that figures out the type, based on some value in a hidden field, and then serializes it using that type.
The first approach is much more preferred because the default model binder works well out of the box, and it's a lot of maintenance to build custom model binders.

Render different view depending on the type of the data (asp.net MVC)

So lets suppose we have an action in a controller that looks a bit like this:
public ViewResult SomeAction(int id)
{
var data = _someService.GetData(id);
...
//create new view model based on the data here
return View(viewModel);
}
What I m trying to figure out is the best way to render a diferent view based on the type fo the data.
the "_someService.GetData method returns an data that knows its out type (ie not only you can do typeof(data) but also you can do data.DataType and you ll get an enum value
so I could achieve what I m trying to do doing something kinda like this
public ViewResult SomeAction(int id)
{
var data = _someService.GetData(id);
//mapping fields to the viewModel here
var viewModel = GetViewModel(data);
swtich(data.DataType)
case DataType.TypeOne: return View("TypeOne", viewModel); break;
...
}
But this does not seem to be the nicest way, (I dont event know if it would work)
Is this the way to go?
Should I use some sort of RenderPartial Aproach? after all , waht will change in the view is mostly the order of the data (ie the rest of the view would be quite similar)
Cheers
Try this:
public ViewResult SomeAction(int id)
{
var data = _someService.GetData(id);
var viewModel = GetViewModel(data);
return View(data.GetType().Name, viewModel);
}
Then just name your views accordingly.

Resources