MVC: Displaying dynamic forms based on URL arguments - asp.net-mvc

I am trying to generate content within a view based on a URL parameter.
For example:
10 companies, 30 users each
A user from company Google clicks a distributed icon that opens
www.****tickets.com/ticket/?c=Google
A custom ticketing page with textboxes, dropdownlists with
'Google-specific' categories and the Google logo is displayed.
All of this data will be handled by a common controller
I have lots of plans for this site, but this is step #1. I am pretty new to MVC, but I have a page propped up that has Users/Groups/Roles. I'm unsure if there would be a better way to implement this, such as Javascript.
EDIT: It looks like MVC Dynamic Forms could be useful for this application. Researching it now.

Your controller method for handling the URL /ticket should accept an optional parameter c. This will then automatically be populated by the value in the querystring. You can then hold this in a model and pass it into the view.
The code will be something like
[HttpGet]
public ActionResult Ticket(string c = null)
{
//Get some data based on c
var model = new TicketModel
{
Company = c,
SomeDropdownValues = StuffYouReadFromTheDbUsingParameterC,
LogoPath = PathYouHaveCalculatedUsingParameterC
};
return View(model);
}
If you don't know how to use a model within a view look up the term "model binding". This article explains it clearly.

Related

How to pass get parameters with the same key twice in asp.net MVC RedirectToAction?

I'm developing a asp.net mvc website for an intranet system. In this system, I have several pages with grids. I am using the Grid.MVC extension to build these grids.
Grid.MVC supports the filter function based on GET parameters. For example, if I want to filter the column name where name = "michael", I need to pass a url GET parameter like this: ?grid-filter=name__1__michael;. The number 1 refers to the type of filter, equals in this case.
It supports multiple filters too. To use this, I need to pass the grid-filter parameter multiple times, like ?grid-filter=name__1__michael;grid-filter=age__1__21. I don't know how to pass the grid filter multiple times when I am returning a redirectresult from an action. Does anybody know how to do this?
Having searched awhile to solve the problem myself, plus if I understand you correctly, I think what you want to do is to PASS (multiple-times) SAME PARAMETER to controller.
Definitely as your questions states, it can help to redirect to the appropriate page while retaining all the data.
Here is a simple MVC example with Controller and View.
public ActionResult(List<string> gridfilter, List<string> param2)
{
ViewBag.gridfilter = gridfilter;
ViewBag.param2= param2;
}
Then, to display the values in View, you can do like this on the View Page:
#foreach(var grids in ViewBag.gridfilter)
{
<p>#grids</> //displays current value
}
#foreach(var param in ViewBag.param2)
{
<p>#param</> //displays param 2 value
}
In your Url, you can then post as many value of your parameters as you want.
Example:http://example.com?gridfilter=anystring&gridfilter=anystringagain&param2=anystring

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

How can i do paging in asp.net mvc3?

I am working on asp.net mvc3 application and have many records coming from database. I want to display only 10 records first then user can click on button to see next 10 records and so on... Like facebook wall posting more records.
How can I implement this thing in my application using jQuery and ajax?
How can I control display data in view using paging?
I am using this to get 10 records but I want to display all records using more record button
var Entity = (from a
in context.Data
where <Condition>
select a).Take(10);
The following articles should give you an idea :
http://weblogs.asp.net/andrewrea/archive/2008/07/01/asp-net-mvc-quot-pager-quot-html-helper.aspx
http://weblogs.asp.net/gunnarpeipman/archive/2010/02/21/simple-pager-for-asp-net-mvc.aspx
On the other hand, you can implement it like this :
Get the nuget package called TugberkUg.MVC
Then, your controller should look like below :
public ActionResult Index(int page = 0) {
const int pageSize = 10;
#region _filter the model
IQueryable<myModel> model = _myrepo.GetAll()
#endregion
#region _convert the model to paginatedList
var paginatedModel =
new TugberkUg.MVC.Helpers.PaginatedList<myModel>(model, page, pageSize);
#endregion
return View(paginatedModel);
}
And, here how your controller should look like :
#model TugberkUg.MVC.Helpers.PaginatedList<myModel>
#foreach(var item in Model) {
<p>#item.id</p>
}
You need to handle the pager as well and here is a sample for you :
ASP.NET MVC PaginatedList Pager - Put wise "..." after certain point
This TugberkUg.MVC.Helpers.PaginatedList class will provide all the necessary fields for pager.
I'm not aware of any .net library that will do pagination for you out of the box, so I will roll out a DIY solution for you to think about.
How can i implement this thing in my application using jquery and ajax?
It is probably wise to have a specific Controller for ajax requests. Just have a separate Area (Ajax), and send your ajax requests to that url you set up.
How can i control display data in view using paging?
Set up a controller that takes in a "page" parameter.
public ActionResult GetData(int? page){
// page is nullable to allow for default page
// Do your query here to get the specific page.
}
I'm not sure if you require more information other than this. If I were trying to do what you were doing, this is what I would do. Hope that helps.
If your are using Webgrid to display data then rowsperpage will do.
var grid = new WebGrid(source: Model, selectionFieldName: "SelectedRow", rowsPerPage: 10, canPage: true, canSort: true);
I would suggest using a telerik mvc control. They are really easy to use, powerful and free.
www.telerik.com

ASP.NET MVC URLs - Correct approach

Currently my project has a page domain/cocktail which displays a list of all cocktails. If user wants to filter the list he can choose sorting order, cocktail's starting letter and strength. So url will look like domain/cocktail?letter=B&sort=nu&strength=2&page=4.
As I've read it is not the best choice to use such urls. What approach can you suggest to get SEO-friendly URLs with the same functionality.
ASP.NET MVC applications use the ASP.NET routing system, which decides how URLs map to particular controllers and actions.
Under default routing system when a browser requests http://yoursite/Home, it gets back the output from Controller's action method. Therefore if you use CoctailList action method to derive the list from backend, user will need to point at http://yoursite/Controller/CoctailList
In your situation, I would POST the search criteria, but I would put the page on end of the URL like:
domain/cocktail/2
domain/cocktail/3
You can post the data by creating a JSON object:
var viewModel = new Object();
viewModel.Letter = "B";
viewModel.Sort = "nu";
$.post("/domain/cocktail/" + page, viewModel, function () { });

asp.net-mvc - how do i create a view to show all unapproved users and allow them to be approved

i have this code in my membership service class (taken from the asp.net-mvc sample app)
public MembershipUserCollection GetUnapprovedUsers()
{
MembershipUserCollection users = Membership.GetAllUsers();
MembershipUserCollection unapprovedUsers = new MembershipUserCollection();
foreach (MembershipUser u in users)
{
if (!u.IsApproved)
{
unapprovedUsers.Add(u);
}
}
return unapprovedUsers;
}
i now need a view to show this list of information and allow someone to approve them which will go back to the controller and set the IsApproved property to true.
Create a view which will generate a form containing label and checkbox for each member of the collection. You need to be able to get from the id of the checkbox to the user.
In the HTTP.POST Action method, iterate through the submitted fields looking for set checkboxes, when you find one set the corresponding user to approved.
Obviously the form can display arbitrary details for each user.
To use the inbuilt control helpers takes a bit more effort because you don't have a fixed size model to work with. To achieve something similar I:
Used a non-strongly typed view
populated ViewData["ids"] with IEnumerable<IdType> (which the view would loop over)
For each entry populated ViewData["field" + id] for each field I was displaying in the entity
In the view looped over the ids using ViewData["ids"] to call the HTML helpers with the id of the field.
(That was V1, in V2 I used model state so I could use the inbuilt validation error display support, but that doesn't really apply if you just want to select users.)
The POST processing was similar, repopulating the id list from the database and the looking up in the passed FormCollection.

Resources