Passing and Storing objects between Pages - asp.net-mvc

I'd like some advice on this issue. Basically, I have 2 pages (for simplicity sake), and the second page is completely dependent on the first page.
So lets say the main page is a search page, and the second page is a view page.
The site works off XML requests, and the ultimate aim is to keep the XML requests to a minimum as each request is a little slow. I considered using Sessions, but I've had some problems in the past with sessions being mixed between users randomly which i only manage to curb by changing the recycle process in IIS to a very small time frame, so I'm wondering if there is any other way. I've tried TempData, but that expires after one request, so a page refresh on the view page doesn't seem possible. (or is it?)
Anyways, we have the Search page that has, say, 5 attributes that are required by the View page, but only 2 are needed to make the XML request on the view page.
e.g.
Search Page Contains:
ID,
Name,
City,
Email,
Height
View Page needs the following from the Search page to complete the xml request:
ID,
Name,
Email
View Page displays all the information from the search page, plus everything in the XML response.
The link i have in the search page only has the ID in the url, so name and email are required for the XML request on the second page some how. Not sure if it's possible without sessions?
What i've tried is:
Store the search results in TempData. That way, when someone clicks the 'View' link (View), the View page loads the search results like so:
var viewPage = SearchResults.Where(w => w.ID == id).FirstOrDefault();
The ViewModel then renders the page by grabbing the Name and Email from viewPage, making an XML request, and displaying the response, along with other required details from viewPage.
It works as expected with tempdata. Data only persists on the first request, dies on a page refresh. Sessions is the alternative, but is there any other?
(sorry for the wall of text :)

Why not using more standard techniques like a <form> tag in the search page pointing to the controller action that will perform the search:
#using (Html.BeginForm("search", "somecontroller", FormMethod.Get))
{
... some input fields for your search criteria
<button type="submit">Search</button>
}
and then you will have the Search controller action:
public ActionResult Search(SearchModel model)
{
var results = ....
return View(results);
}
I've used GET method on the form which allows the user to bookmark the results page and come back to it later.

Related

Multiple pages, single controller, how to set it up in mvc?

I have a 'home' controller which deals with the basic Home, About, Courses, Contact pages. There are multiple courses available, each with their own page and I would like to know the best method for referencing these pages. I could just create them as additional pages and add an actionresult to the home controller for each page. So the url for a course would be home/course1. Presumably there is a much better method than this though.
Ideally I'd like to have the individual course pages in a separate folder within the view folder and their url to be /home/courses/course1. Can anyone explain the best method using MVC for organising these pages?
So it goes like this : There will be a single page for all the courses and all the course pages will be partial views now there will be a div on the main page and whenever user clicks one of the course name.. it will fire an ajax request and it returns the required partial and populate the div with the returned content. You can give a common class to all the links of Courses, just like this :
.<a class="couseTrigger" data-source="#Url.Action("Name of Partialview action,"
name of controller")">
------ Script -----
$('.couseTrigger').click(function(){
var _this = $(this);
var url = _this.data('source');
--then make the ajax request to this url pvariable and retrun the partial view.
});
If you have multiple courser avoid creating multiple webpages for those courses. Rather have the content of each course stored in a database and retrieve specific course content by some parameter and bind it to the webpage. Creating webpage for each course is not feasible. Suppose you have 100 courses are u gonna create 100 webpages ?

Hiding URL Parameters from Controller to View: MVC 5

Say I have a website with a wide variety of different pages, each tailored for an individual user and accessible only by that user. When a user accesses a page, the URL for that page will be UserStuff/Pages/11, where 11 is the page's ID. Right now, because users can have multiple pages, I am using an ActionLink element to direct the user to their selected page, like so:
// In Index.cshtml
// ...
#Html.ActionLink("View Page", "Pages", new { id = page.ID }, new { #class=...})
The controller intercepts the given id:
public ActionResult Pages(int id)
{
// ...
Page page = db.Pages.Find(id);
return View(page);
}
This works well and delivers exactly how I want the application to behave. However, I wish for the ID to be hidden in the URL. How do I pass information from the View to the controller via a parameter without having it exposed in the URL? Say that I don't want the Page's ID visible in the URL, how can I link to a different Action that takes the given parameter?
I believe that keeping the request a GET request is important due to other actions redirecting to the resulting page. Wrapping it in a form/POST request would make said actions unable to access the information without having to go through the same process as the original user, which is not something that I want in this implementation.

ASP.NET MVC - Complicated view logic

I'm making the transition from webforms to MVC (I know, 3 years late) and I "get it" for the most part, but there's a few things I'd like advice and clarification on:
First off, what happens if you want to dynamically add inputs to a view? for example, in an old webform for generating invoices I had a button with a server-side click event handler that added an extra 5 invoice item rows. The stateful nature of webforms meant the server handled the POST event "safely" without altering the rest of the page.
In MVC I can't think how I'd do this without using client-side scripting (not a showstopper, but I would like to support clients that don't have scripting enabled).
The second problem relates to the invoices example. If my Model has a List, how should I be generating inputs for it?
I know data binding is a possible solution, but I dint like surrendering control.
Finally, back to the "stateful pages" concept - say I've got a Dashboard page that has a calendar on it (I wrote my own calendar Control class, the control itself is stateless, but can use the webform viewstate to store paging information) - how could a user page through the calendar months? Obviously POST is inappropriate, so it would have to be with GET with a querystring parameter - how can I do this in MVC? (don't say AJAX).
Thanks!
In MVC you design your actions to accommodate your needs. For example, if you wanted to be able to add 5 rows to an invoice NOT using client-side scripting, you'd probably have your GET action for the invoice generation take a nullable int parameter for the number of rows. Store the current number of rows in the view model for the page and generate a link on the page to your GET action that has the parameter value set to 5 more than the current value. The user clicks the link and the GET view generates the page with the requested number of rows.
Controller
[HttpGet]
public ActionResult Invoice( int? rows )
{
rows = rows ?? 5; // probably you'd pull the default from a configuration
...
viewModel.CurrentRows = rows;
return View( viewModel );
}
View
#Html.ActionLink( "Add 5 Lines", "invoice", new { rows = Model.CurrentRows + 5 }, new { #class = "add-rows" } )
You would probably also add some script to the page that intercepts the click handler and does the same thing via the script that your action would do so that in the general case the user doesn't have to do a round trip to the server.
<script type="text/javascript">
$(function() {
$('.add-rows').click( function() {
...add additional inputs to the invoice...
return false; // abort the request
});
});
</script>
Likewise for your calendar. The general idea is you put enough information in your view model to generate all the actions that you want to perform from your view. Construct the links or forms (yes you can have multiple forms!) in your view to do the action. Use parameters to communicate to the controller/action what needs to be done. In the rare case where you need to retain state between actions, say when performing a wizard that takes multiple actions, you can store the information in the session or use TempData (which uses the session).
For things like a calendar you'd need the current date and the current view type (month/day/year). From that you can construct an action that takes you to the next month/day/year. For a paged list you need the current page, the current sort column and direction, the number of items per page, and the number of pages. Using this information you can construct your paging links that call back to actions expecting those parameters which simply do the right thing for the parameters with which they are called.
Lastly, don't fear AJAX, embrace it. It's not always appropriate (you can't upload files with it, for example), but your users will appreciate an AJAX-enabled interface.
In MVC you can store application state in various ways. In your controller you have direct access to the Session object and you can also store state to the database.
your view can contain basic control flow logic, so, if your model has a list you can iterate over it in the view and, for example, render an input control for each item in the list. you could also set a variable in a model to be the maximum number of rows on the viewpage and then render a row in a table for the number specified by the model.
paging is basically the same thing. you can create a partial view (user control in the webform world) that shows page numbers as links, where each link calls an action that fetches the data for that page of results.
i'm not sure what your beef is with ajax or javascript

MVC Paging and Sorting Patterns: How to Page or Sort Re-Using Form Criteria

What is the best ASP.NET MVC pattern for paging data when the data is filtered by form criteria?
This question is similar to: Preserve data in .net mvc but surely there is a better answer?
Currently, when I click the search button this action is called:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Search(MemberSearchForm formSp, int? pageIndex, string sortExpression)
{}
That is perfect for the initial display of the results in the table.
But I want to have page number links or sort expression links re-post the current form data (the user entered it the first time - persisted because it is returned as viewdata), along with extra route params 'pageIndex' or 'sortExpression',
Can an ActionLink or RouteLink (which I would use for page numbers) post the form to the url they specify?
<%= Html.RouteLink("page 2", "MemberSearch", new { pageIndex = 1 })%>
At the moment they just do a basic redirect and do not post the form values so the search page loads fresh.
In regular old web forms I used to persist the search params (MemberSearchForm) in the ViewState and have a GridView paging or sorting event reuse it.
One possible solution is to attach a javascript click handler to the pager links that will submit the form by updating a hidden field containing the page number. This way you will get all the search criteria in the controller action.
Another possibility is to transform those pager links into submit buttons and place them inside the form.
A third possibility is to use the Session to persist search criteria.
You could perform a GET instead of a POST. if your request is to return search results, a GET might make more sense anyway. The benifit would be that all of your search fields are encoded into the URL. So, when you perform a page or sort on th exisiting URL, your data is perserved.
I have an example that using the MvcContrib Grid and Pager here:
http://weblogs.asp.net/rajbk/archive/2010/05/08/asp-net-mvc-paging-sorting-filtering-using-the-mvccontrib-grid-and-pager.aspx

Persisting data from multiple forms in ASP.NET MVC

I have two forms on one page: a results form and a search form. The search form uses a partial view because it is displayed on several different pages. I want to be able to persist the data in the search form regardles of which button on which form the user clicks. The problem is that when the user clicks on a link or button from the results form, only the form values from the results form are posted, the values from the search form are not included. How can I maintain the values in the search form even when it is not the form that is submitted? I do not want to use any type of session state to maintain the form and I dont want to write the search values in hidden fields in the results form. I just want to be able to post them with the form values of the results form so that the users search criteria can be maintained accross any page that displays the search partial view. What am I missing?
The first thought that occured to me is to remove the form wrapping the search control and just let it be rendered into the form with the results data. I worry here about naming conflicts. What happens when the search from has a control with the same name as the results form, wouldn't this cause a naming conflict? I suppose that this could just be managed manually to ensure that there are unique names whenever rendering partial views into other views, perhaps even going so far as to prefix values with the partial view name, but that reminds me of the ugliness that is INamingContainer in web forms - plus makes for cumbersome field names in your model.
Is there some sort of elegant solution that will allow a form to persist state that I am missing? Thanks!
Normally, I persist the search criteria on the server side when the search is performed. If the user changes the search criteria after performing the search, then posts the form any changes are, of course, lost but that's arguably correct behavior since the search wasn't invoked. This is true whether the search is performed from a full post or via ajax. Handling it this way keeps the actions cleaner, I think as you don't need to handle the search data in the other actions.
If you absolutely need to have the search parameters included, you could consider having the second form post via javascript, pick up the search field values dynamically and add them to the second form (as hidden fields) prior to posting the second form. You wouldn't have to maintain the values in two places in synchronization, but you would have to copy them to the second form before posting.
At the moment i got it like this:
Forms which has search box, posts query (and additional data if needed) to search controller which then renders search view. Search view is made from search box and search results partial views. During this - search box form is reconstructed by posted data.
If i need search results form to perform another search request (for example, with specified page index), it goes through ajax, which posts search box form + page index from search results form. Take a look here for ideas (update that JS method with targetId parameter for updating specified div/form and post additional data if needed here like this:
form.serialize()+"&pageIndex=5"
In short: if you need to maintain state of form + update another in one page - consider using partial updates, otherwise you will end up inventing ViewState 2.0.
One caveat with this way - it's tricky to make search box contain something what is related with search results (i.e. - total count of found items). Before i managed to handle this, our designer did that - i just need to add div with appropriate class name ("sbsubst" or something) and it looks that it's inside search box. :)
When you have few forms at your page each form sends only its own data. In WebForms you had only one form (at least server-side) and each control was included into this form. In ASP.NET MVC you can use the same scenario and I'm afraid you will have to if you want to have the described behavior. Don't forget - partial forms don't have to be real forms. Moreover, RenderPartial is mostly used for "control-like" layout creation.
As for the second part of your question I would suggest naming your text boxes in search form with some normal prefix like "search" or something like that. For instance, if you have text box "text" and "language" in the form, you will have "searchText" and "searchLanguage". These names are quite unique and you will have normal names in your parameters.
I am not suggesting you populating the hidden values in your results form on POST event since you said it's not an option for you but still it may be the only way if you want to have two forms.
I think the best approach will be storing the text from search input when it changes in the query part of your second form action url. For example (not tested):
$('input#yourSearchInput').change(function()
{
var searchText = $(this).val();
// or? var searchText = encodeURIComponent($(this).val());
var secondForm = $('form#secondFormId');
var action = secondForm.attr('action');
var queryStart = action.lastIndexOf('?search=');
if(queryStart > -1) {
action = action.substring(1, queryStart);
}
action = action + "?search=" + searchText;
secondForm.attr('action', action);
});
In Controller (or custom filter):
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var search = Request.QueryString["search"];
if(!String.IsNullOrEmpty(search)) {
ViewData["SearchFromPOST"] = search;
}
base.OnActionExecuting(filterContext);
}
In your Search Control:
<%= TextBox("yourSearchInputId", ViewData["SearchFromPOST"]) %>

Resources