I'm passing structured data to my MVC page when it loads initially. After the user submits a contact form, I want to re-use the same data (I just "leave" the same page up) so I don't have to hit the database again. I declared a variable global to the controller to store the model data, but it's null at the end of the post back, so it looks like I can't re-use it there.
Seems like this would be a typical scenario. How do I handle it?
If you are wanting to reuse viewmodel or other retrieved data that is not going to be part of the postback, you can either
a) Output it in hidden fields so that it is posted back to your action (meh) or
b) Store the object(s) in Session so that it will be available to any other controllers/actions in your application. If you are worried about memory, you could delete that session variable after you reuse it if you are not going to need to use it again.
On your initial page load, check if the session variable exists, if it does, you are good - else populate it.
Oh and why the global variable thing isn't working -> a controller is new'd up for each request (assuming using the default controller factory) and as such any global variables in the controller will be reset on each request.
public ActionResult Foo()
{
var model = GetModelFromDB();
Return View(model);
}
[HttpPost]
public ActionResult Foo(Entity model)
{
Return View(model);
}
Asp.net-mvc is stateless so each HTTP request has a different context, and each time you hit the controller all it's data reset in the constructor, this why you get null.
You can get the model in the post if it's properties are within the submitted form .
If you really don't want to leave the page you are on, and don't want to post all the other data back as KMan suggests, but still want to capture the users contact information/data you could post the contact info using ajax.
If you have your view model as an argument to your method, you can just return it to the view on postback. Ex:
public ActionResult TestAction(MyViewModelType testViewModel)
{
//Do logic
return View("view",testViewModel);
}
Note that you have to have the data inside the form you are posting.
Related
As I have read that once you set a tempdata, it will last till next request and if you need to use it more then we need to use keep. But in this situation there is somewhere my tempdata is being lost.
The scenario is below:
I have a view and corresponding to that I have a action method in my controller and here I just set a tempdata as below:
Controller class:
public actionresult myview()
{
tempdata["Empid"]= sourceid;
}
The view consists of several renderAction as below and all these actionmethods in controller return some partialviews
#html.renderAction("details","mycontroller")
#html.renderAction("details","mycontroller")
#html.renderAction("details","mycontroller")
#html.renderAction("details","mycontroller")
Now in partialviews, I have several ajaxified calls suppose in one of the partialview , I have a post method using ajax like below:
$.post("action", "controller",{}});
Please ignore syntactical mistakes as I only have problem in understating the logic of tempdata.
So, coming to above, now the post methods have actionmethods that uses the tempdata that i have set when my view page loads i.e tempdata["Empid"] because this tempdata is needed to get details of employee.
So, it gets the data, reurn json formatted data and I show it in view perfectly.
Uptill here everything is fine. Now, I have one of the partialviews that uses the ajax post to hit controller which is not the same controller but a different cs file. Here this tempdata goes off.
Why is it happening so..
TempData is designed for a short life by default. So the data you set to TempDataDictionary object persists only from one request to the next request. After that it is not going to be available.
You can use the TempDataDictionary.Keep() method to persist the value for the next request again.
public ActionResult Index()
{
TempData["Message"]="Hello";
return View();
}
public ActionResult GetCustomer()
{
var msg = TempData["Message"] as string;
TempData.Keep("Message");
return View();
}
I have 3 partialviews with 3 viewmodels on page:
List of accounts
Modal popup (you can modify multiple accounts here)
Search panel
I want to refresh 1. after doing POST on 2. This is straightforward, but what if I want to keep results I got after using Search Panel?
I can do this in 2 ways but both seems bad (correct me if I am wrong).
First (the one I chose and works) is to store viewmodel used in 3. in TempData. I do Search (POST) and save passed viewmodel in TempData. Then whenever I do POST on different partialview I can refresh 1. using data(search parametrs) from TempData.
private const string SearchDataKey = "SearchData";
[HttpGet]
public PartialViewResult RefreshData()
{
if (TempData[SearchDataKey] != null)
return PartialView("AccountListView", PrepareAccountListViewModelForSearchData(TempData[SearchDataKey] as AccountSearchViewModel));
else
return PartialView("AccountListView", PrepareAccountListViewModel());
}
and saving ViewModel:
public PartialViewResult Search(AccountSearchViewModel searchParameters)
{
...
TempData[SearchDataKey] = searchParameters;
return PartialView("AccountListView", databaseAccountListViewModel);}
Second approach is to always POST "big" viewmodel with all 3 viewmodels. This way I will have data from Search's viewmodel but I will send many not needed information instead just Modal Popup's viewmodel which I need to call procedure.
I asked few MVC folks with better experience and they said they never had to store viewmodel in TempData but it still seems more reasonable than having 1 Big form and passing everything in every POST.
Do you know any better ways to handle this or which one is correct?
PS. Topic had "Best Practice" but was removed cause of warning message. I hope asking about opinion is still allowed on SO.
PS2. Most of my POSTs & GETs after initial load are through Ajax.
I do Search (POST)
This seems semantically incorrect to me. Searching is an action that shouldn't modify any state on the server. So using GET seems more appropriate. And when you use GET you have the benefit that all parameters are already present in the query string and thus preserved upon successive POST actions (like modifying an account in your case). So your RefreshData action could take the AccountSearchViewModel as parameter and the model binder will take care of the rest.
So I have a ViewBag.Something and this data is randomly generated. In my view, I set this to a label like so #Html.LabelFor(m => m.Something, (string)ViewBag.Something). This works out well but when I submit the form there could be errors and if there are errors, I need this label to remain the same, I don't want dynamic/random data anymore so I wouldn't call the controller method that generated this ViewBag. Is there a way to retain this value without having some private variable in my controller? Some nice way that MVC/Razor does it?
Option 1:
Pass the value of "ViewBag.Something" to the Controller by using route Values:
#Html.ActionLink("ButtonText", "ActionName", new { Something = #ViewBag.Something })
Option 2:
You can use TempData.
public ActionResult Index()
{
var Something = "YOURVALUE";
TempData["Something"] = Something;
.......
}
public ActionResult OtherAction()
{
var Something = TempData["Something "];
...........
}
Passing State Between Action Methods
Action methods might have to pass data to another action, such as if an error occurs when a form is being posted, or if the method must redirect to additional methods, as might occur when the user is directed to a login view and then back to the original action method.
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
In the get, set up a model, set it dynamically and when return view() is being executed, do return view(model). Then in the view, set up a hidden field that can keep on passing the value needed. I chose to go this route because I don't have to worry about any server code to make this work on a post and I don't have to worry about any sessions.
Displaying message in viewbag after posting (I user this method)
ActionResult SubmitUser(){
ViewBag.Msg =TempData["Msg"];
return view();
}
[HtttpPost]
ActionResult SubmitUser(){
TempData["Msg"] ="Submitted Successfully"];
return view();
}
The Value is send to get method..
I really need to maintain this string called "filterParams" in my MVC application. After the user enters some search parameters he clicks submit, and the grid is rebinded with that parameter. That works great. I also save the filterParams data in a Javascript variable, so when the user pages, and the OnDataBinding event is raised, the filter is also passed through that ajax call as well. this is all well and good however there is a huge issue, because when the user updates a question, all the results dissapear because it returns to the View and it does not have any data there. The way I'm using ViewData isn't working, and I could use your help, because if I can store it in ViewData and access it, it would fix my problems. I cannot use TempData because there are a number of other Actions that can be called in between Select and Update...Long question short, how do I implement ViewData correctly to store and retrieve a string in my controller?
Here are some code snippets.
[GridAction]
public ActionResult GetAllQuestion(string filterParams)
{
var _filterParams = new List<string>();
_filterParams.Add(filterParams);
ViewData["filterParams"] = _filterParams;
return View(new GridModel(QuestionManager.Instance.GetQuestion(filterParams)));
}
[GridAction]
public ActionResult EditQuestion(int id, QuestionDTO pQuestion)
{
// var _question = QuestionManager.Instance.GetQuestion(id,false).FirstOrDefault();
// TryUpdateModel(_question);
var _filterParams = (List<string>)ViewData["filterParams"];
var filterParams = _filterParams[0];
QuestionManager.Instance.UpdateQuestion(pQuestion);
// return View(new GridModel(QuestionManager.Instance.GetQuestion(id, false)));
return View(new GridModel(QuestionManager.Instance.GetQuestion(filterParams)));
}
in my aspx page
Html.Telerik().Grid<QuestionDTO>()
.DataBinding(dataBinding => dataBinding.Ajax().Select("GetAllQuestion", "Question", new { filterParams = string.Empty }).Update("EditQuestion", "Question").Insert("CreateQuestion", "Question"))
How can I get this to work please? Help is appreciated
ViewBag/ViewData only works for sending data from an action to a view. It does not get populated by the Model Binder when a request is made to an action, and its state is not saved between requests because ASP.net MVC is entirely stateless. In other words, the ViewData dictionary is always empty at the start of a request.
Meaning this line in your EditQuestion action will not work:
var _filterParams = (List<string>)ViewData["filterParams"];
ViewData is empty, so _filterParams will be null.
You have to manually send filterParams to the EditQuestion action just as you do for the GetAllQuestions action.
Perhaps a better alternative would simply be to persist filterParams using a temp cookie on the client side.
So, just to defy all the misinformation I've read on the subject, TempData infact does persist through multiple action calls in the controller and was able to be used to implement the functionality I needed.
Why just not store the data in Session?
Here's a good explanation with examples
http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
Just wondering, I strongly type these views in ASP.NET MVC and then use Request.Form on the submit controller to get the data out, validate it, put it in an object, send to database. Is there a way I can just send the object back from the View page since it is strongly typed instead of doing all this crap to just end up with an object again since I just started with one anyways?
You mean, model binding?
[AcceptVerbs (HttpVerbs.Post)]
public ActionResult UpdateUser (User user)
{
SaveUpdates ();
return View();
}
This will automatically initialize the User properties with the form values with the same names.
Look at this answer: ASP.Net MVC Custom Model Binding explanation
(source: odetocode.com)