Pass MVC view value to controller - asp.net-mvc

I am displaying a value on my MVC view using a query string. For example ..
in my view I have:
<h3>Selected Game <%=Request["GameId"]%> </h3>
This displays the gameid selected by user on the view (via a query string)
Now I want to be able to use this value displayed on the view and run a query in the controller/service layer code. How can I pass this value to the controller.

You can access the Request the same way from the controller.
string gameid = Request["GameId"];
I would caution you, however, about trusting values you get from the request. This is where hackers like to strike, by entering their own values, which may not even be numbers.
Validate all data you get from the client, including querystring parameters.

You can't pass it to the same controller .. The view is already rendered. You seem to know about ajax, so it's just a simple matter of making another request. Make an ajax request to the controller in question with the GameId parameter.

Related

Storing information between requests in form fields

After brief research, I've found in one of SO thread that there are three most popular ways of storing information between requests in ASP.NET MVC:
Storing information in form fields in the view, and post it back to the controller later
Persisting it in some kind of storage, e.g. a file or a database
Storing it in server memory by acessing objects that lives throughout requests, e.g. session variables
How does the first method work? I mean, I can have a controller that returns a view + viewmodel accessible from this view. The user does something in the view and request an action from the server. Now, the action will perform on server side and it will return another view. So anything I store in the HTML form fields will be gone after requesting any action from the server.
I guess the only way is to POST form fields to the server and then send it back with the returned View. If I don't post them from the view, the modelview object data are gone. Or maybe there's another way I'm not aware of?
If you need to store some information between requests you can use hidden fields. For example first view contains hidden fields FirstName and LastName.
You post some data to your controller and these data are mapped to some view model in action. In this case you should either add you FirstName and LastName properties to this view model or add them as additional action parameters.
From this action you want to pass FirstName and LastName to another view:
You can create another view model that contains these properties and initialize them in action
You can use storages like ViewBag, ViewData etc.. to pass FirstName and LastName without adding them to view model.
But if you don't want to send FirstName and LastName through hidden fields you can use TempData storage. Add these parameters in first action that renders some view and you can read them in another action.
Read this article for the details.

Sending Parameters when opening mvc view

In my Controller I return the View for a specific model by
return View(model);
(Nothing magic there). Now this view contains a lot of Elements like different tabs. I want to send and receive a parameter to that view so I can display a specific tab depending on the parameter I send.
How can this be done?
There are two questions in one. I will answer them one by one:
Passing information to view
One option is to use ViewBag. Second is to extend your model to contains information about which tab should be passed
Passing information from client
In action link you have to generate parameter to pass which View should be open. This parameter will be attached to query string so you can easy map it to input parameter for controller or read it from query string.
You can using ViewBag or ViewData.
In your controller
ViewBag.test = "some text";
In your view
#ViewBag.test

MVC checkbox checked state issue

Good morning,
I have a view that display's search results for customers. On top of the view i have a filter that has a few checkboxes. The user can select multiple checkbox items and press the filter results button. When the user presses the button it calls an action that filters the result. The page is also refreshed. My question now, how can i make the page remember what checkboxes are checked. Because when the results are returned the filter elements are reset.
Thanks in advance.
you can use TempData. TempData VS ViewBag VS ViewData
you used ViewData, After the redirect, the ViewBag & ViewData objects are no longer available
TempData is also a dictionary derived from TempDataDictionary class
and stored in short lives session and it is a string key and object
value. The difference is that the life cycle of the object. TempData
keep the information for the time of an HTTP Request. This mean only
from one page to another. This also work with a 302/303 redirection
because it’s in the same HTTP Request. 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. Temp data use during the current and subsequent request
only means it is use when you are sure that next request will be
redirecting to next view. It requires typecasting for complex data
type and check for null values to avoid error. generally used to store
only one time messages like error messages, validation messages.
TempData["CheckedList"] = YourCheckBoxListValues; //in your controller
in your View
#{
var tempchkboxList = TempData["CheckedList"] as yourStronglyTypeClass;
//or
var tempchkboxList = TempData["CheckedList"].ToString();
}
Depends on how long the input criteria should be remembered.
You could also save it in your session via Session["customerCriteria"] = yourCriteria, but it would be easier to give an example if you had provided some code.
You can keep your selected/checked checkbox details in session variable when you post the form (by clicking on the search button). In the HttpPost action,read the checkboxes which were checked and add that to a collection property of your viewmodel and send it back to the view. set the session variable values to null once you are done with it (after reading). in the view, use your viewmodel value to set the checked status of those checkboxes.
Another option is using ajax. When you click on search.Read your search criteria and make an ajax request to the action method. Return a partial view back and update only the div/table which shows the results of the search.

ASP MVC3 Pass additional params with "return View(model)"

I'm in serious need of passing url params with View class. Here's code:
if (!ModelState.IsValid)
{
return View(model);
}
This should not only return model based view, but also add specific param to URL (param won't change view details, but is needed as it's one of few automatically generated SessionKeys (one for each tab/window used to view app) and I know no other way to get to it, different than passing as param (it can't be generated everytime, 'cos params will change; it can't be global variable because it'll reset its value each refresh; it can't be static, because static is evul).
Oh this action is called with use of form and submit button, not actionLink or something like this.
EDIT1: I need params to stay in URL after refresh, or I need some other form of keeping data that persists through refresh/validation fail.
If I understand you correctly you have data that you need to use in generating Urls on your page? This just forms part of your ViewModel - or at least it should, since it's data that the View needs in order to render.
You can use ViewData to add any extra data that isn't part of your view model. Or, better still, add the data as members to it. Equally, if different views with different View Models require this data, add a ViewModel base class and derive from that so you can share that data.
use
RedirectToAction("actionName","controller",
new RouteValueDictionary(new {param1="value",param2="value2"});
or you can use hidden field to store the values in your page and then pass this down as and when you need them..

Why do my viewmodel properties end up null or zero?

I'm working on my first MVC application, still figuring it all out.
I have a viewmodel which, at this point, is identical to my domain object. My controller builds the viewmodel and passes it to a view. The view only displays a some of the properties because I don't want primary and/or foreign keys displayed for the user yet, in the case of a primary key, I need to have the data in order to update / delete the database.
It appears that unless I use a viewmodel property in the view, it is set to default values (0 for numeric value types and null for reference types) when I pass the viewmodel back. Is this correct behavior?
I confirmed the viewmodel passed to the Edit view does contain all the properties (as I would expect).
The question - Once a view is rendered, what happens to the viewmodel? If my viewmodel contains properties that are not used in the view, do their values just disappear? For example, when I click the Edit actionlink to fire the Edit action on the controller, the viewmodel that gets passed to the action does not contain any properties unless they are visible on the screen. Why?
BTW, this is ASP.NET MVC 4 RC.
It appears that unless I use a viewmodel property in the view, it is
set to default values (0 for numeric value types and null for
reference types) when I pass the viewmodel back. Is this correct
behavior?
Yes, when you invoke a controller action you need to pass all the properties that you want to be bound in the request. So for example if you are using a html <form> to call the action you need to use input fields. You could use hidden fields but they must be present, otherwise nothing is sent to the controller action
The question - Once a view is rendered, what happens to the viewmodel?
It falls out of scope and is eligible for garbage collected.
If my viewmodel contains properties that are not used in the view, do their values just disappear?
Absolutely. But even if you use those properties inside the view they disappear. For example if you only display the values inside the view but do not use input fields to send them back to the server when the form is submitted they will be gone as well.
For example, when I click the Edit actionlink to fire the Edit action
on the controller, the viewmodel that gets passed to the action does
not contain any properties unless they are visible on the screen. Why?
Because the view model no longer exists. It's gone and garbage collected. That's how the HTTP protocol works. It's stateless. Nothing is persisted between the requests. You will have to include whatever properties you want to be populated in the request either as POST form values or as query string parameters if you are using action links or whatever.
If the user is not supposed to modify those values inside the view you could then simply pass an id to the controller action which will allow for this controller action to retrieve the model from wherever it is stored (a database or something) using this id.
If your properties are in any helper methods which generates the input HTML element inside a form, It will be available in your HTTPost action method when you submit the form. If you are simply displaying it in a div/span , it is not going to get you the property values. That is how MVC model binding works.
Expect the values in your HttpPOST action if you use these HTML helpers
#Html.TextBoxFor
#Html.DropDownFor
#Html.EditorFor
#Html.HiddenFor
Dont expect the values if you use these
#Html.DisplayFor

Resources