What is the controller syntax for sorting multiple MvcContrib Grids? - asp.net-mvc-3

I can't quite figure out the syntax for sorting multiple MvcContrib grids. I know the recommendation from Jeremy Skinner here is to use the Bind attribute but I just can't get it right.
Here is my controller:
public ActionResult Index([Bind](Prefix="grid1")GridSortOptions sort)\\how do I reference the prefix of my second grid?
{
ViewData["sort"] = sort;
var products = _productService.GetAllProducts();
var categories = _categoryService.GetAllCategories();
//Here is where I am stuck
if(sort.Column != null)
{
products = products.OrderBy(sort.Column, sort.Direction);
//how do I reference the sort columns of my second grid?
}
var model = new ContainerModel
{
Products = products,
Categories = categories
};
return View(model);
}
I guess I really don't understand everything about the Bind attribute. I tried adding a second GridSortOptions argument but that was not successful.
Here are my views if this helps.
.Sort((GridSortOptions)ViewData["sort"], "grid1")//Grid 1
.Sort((GridSortOptions)ViewData["sort"], "grid2")//Grid 2
Any ideas? Thanks.

I figured out my problem from my post:
MVCContrib Grid - Sort(GridSortOptions, prefix) not generating links for sorting
It is possible that the default binder is not pre-populating your parameters and so your GridSortoptions are probably null which means no links ultimately.
Also, just create a second GridSortOptions parameter for the second grid and use that in the call to Sort().

Related

How to show custom query result to view mvc3 Razor

I have Custom query Result as
public ActionResult Index()
{
var Query = (from E in db.SITE_MASTER.AsEnumerable()
where E.IS_PAGE == true
select new
{
E.POST_TITLE,
E.POST_TEXT
}).ToList();
return View(Query);
}
Now,
How can I make view for this result or How can I create View for this Result Query.
Thanks...
You can pass an anonymous type as a model, but please don't. It's ugly and will lead to maintenance problems.
As an alternative either use the ViewBag or create concrete type and pass that.

How to access objects inside a List, saved in a Session. ASP.NET MVC 3

So I have this code:
var list = new List<Carrito> {
new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio }
};
Session["list"] = list;
return View();
Then I load the view but I don't know how to print the the content that is inside the session. Any ideas?
This is the code I use inside the view but doesn't work:
#foreach(var item in (IEnumerable<object>)Session["list"] )
{
<p>#item.ProductId</p>
}
it's as simple as reading back the value from your session varable and cast it to the original type, then do whatever you want
example:
#{
if(Session["list"]!= null)
{
var listBackFromSession = (List<Carrito>)Session["list"];
// do what you want
}
}
My recommendation is to use the more elegant way of ViewBag.
a quote from official asp.net mvc website about Viewbag:
New "ViewBag" Property
MVC 2 controllers support a ViewData property that enables you to pass
data to a view template using a late-bound dictionary API. In MVC 3,
you can also use somewhat simpler syntax with the ViewBag property to
accomplish the same purpose. For example, instead of writing
ViewData["Message"]="text", you can write ViewBag.Message="text". You
do not need to define any strongly-typed classes to use the ViewBag
property. Because it is a dynamic property, you can instead just get
or set properties and it will resolve them dynamically at run time.
Internally, ViewBag properties are stored as name/value pairs in the
ViewData dictionary. (Note: in most pre-release versions of MVC 3, the
ViewBag property was named the ViewModel property.)
Further more, This is a good article to read about the different ways you have in MVC in order to preserve data: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
example:
var list = new List<Carrito> {
new Carrito { ProductId = producto.ID , Cantidad = 1, PrecioUnitario = producto.Precio }
};
// use ViewBag
ViewBag.myList = list;
then inside your view, read them back like this:
var myList = (List<Carrito>)ViewBag.myList;
// your code
You're doing MVC fundamentally wrong. In MVC, Views are there only to render a model. The logic of accessing that model should be implemented in controller, or in any other place, but not in the View itself.
Thus I recommend that you simply pass your list to the view, and make your view strongly-typed by including #model List<Carrito> at the top.

Dynamically create random number of dropdownlists in MVC

I need to create a random number of dropdownlists in my view, based on the selected value of another dropdownlist. This is all done but my problem comes when I need to make the httppost because i never know how much data i need to save in my db.
In my model I have a list
public List<RoomToBooking> RoomsToBooking { get; set; }
that will get filled with x number of RoomToBooking when the Create view is rendered after the user makes a selction of dropdownlist 1:
var dogs = from d in db.Dogs
where d.Customer_ID == id
select d;
foreach (Dog item in dogs)
{
roomToBooking = new RoomToBooking();
roomToBooking.Customer_ID = id;
roomToBooking.Dog = item;
roomsToBookingList.Add(roomToBooking);
}
So I would like to create the same number of dropdownlist in my Create view
#Html.DropDownListFor(model => model.Booking.RoomToBooking, new SelectList(ViewBag.DeliveryTypes), new { #class = "selectbox" })
#Html.ValidationMessageFor(model => model.Booking.RoomToBooking)
So I in the end can be able to save it to my db
[HttpPost]
public ActionResult Create(EditBookingPensionViewModel model)
{
foreach (RoomToBooking item in objViewModel.RoomsToBooking)
{
//Save to db
}
}
I assume that I should use jquery to create the dropdownlists, but how do i create the dropdownlists so the selected values can be found in my viewmodel??
You may take a look at the following article. I slight adaption might be necessary for your scenario because you don't have add and remove buttons but instead you use the selected value of a dropdownlist to determine the number of dynamic rows to be added. But the concept is the exactly the same.

MVC 3 Details View

I am new to MVC frame work. And i am making one page where we can see details of department by clicking on details link button.
While User click link button it fetch the all the records of the particular department in List Collection and redirect to Details View.Data has been fetched in List but while going to Details view it Generates following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[DocPageSys.Models.Interfaces.DepartmentInfo]', but this dictionary requires a model item of type 'DocPageSys.Models.Interfaces.DepartmentInfo`'.
I understood the error but confusion to solve it.And stuck with this problem...
Since your Details view is strongly typed to DepartmentInfo:
#model DocPageSys.Models.Interfaces.DepartmentInfo
you need to pass a single instance of it from the controller action instead of a list:
public ActionResult Details(int id)
{
DepartmentInfo depInfo = db.Departments.FirstOrDefault(x => x.Id == id);
return View(depInfo);
}
So make sure that when you are calling the return View() method from your controller action you are passing a single DepartmentInfo instance that you have fetched from your data store.
To make it run fine initially you could simply hardcode some value in it:
public ActionResult Details(int id)
{
var depInfo = new DepartmentInfo
{
Id = 1,
Name = "Sales",
Manager = "John Smith"
}
return View(depInfo);
}
Oh, and you will notice that I didn't use any ViewData/ViewBag. You don't need it. Due to their weakly typed nature it makes things look really ugly. I would recommend you to always use view models.
Passing a list instead of a single item
This error tells you, that you're passing a list to your view but should be passing a single entity object instance.
If you did fetch a single item but is in a list you can easily just do:
return View(result[0]);
or a more robust code:
if (result != null && result.Count == 1)
{
return View(result[0]);
}
return RedirectToAction("Error", "Home");
This error will typically occur when there is a mismatch between the data that the controller action passes to the view and the type of data the view is expecting.
In this instance it looks as if you're passing a list of DepartmentInfo items when your view is expecting a single item.

ASP.NET MVC2 Simple Linq Question

I have the following code:
public ActionResult ViewCategory(string categoryName, string searchCriteria = "Price")
{
// Retrieve Category and its associated Listings from the database
var categoryModel = db.Categories.Include("Listings")
.Single(c => c.Title == categoryName);
var viewModel = new ClassifiedsBrowseViewModel
{
Category = categoryModel,
Listings = categoryModel.Listings.ToList()
};
return View(viewModel);
}
This code returns some listings from a given category.
But I want to re-order these search results based on certain criteria. E.G. Price...
Many Thanks,
J
You want to use OrderBy() or OrderByDescending() depending upon on requirements.
For example ordering it by highest price -
var viewModel = new ClassifiedsBrowseViewModel
{
Category = categoryModel,
Listings = categoryModel.Listings.OrderByDescending(c=>c.Price).ToList()
};
Listings = categoryModel.Listings.OrderBy(x => x.Price).ToList();
Another option that might work, depending on how you present the information: use something like the jquery tablesorter plugin, and sort the results on the client side.
Obviously, this won't work if there are a lot of results, and you're doing paging, but for a single page of results, presented in a table, it works great.
Another way to write the Linq is to use the query language:
Listings = from item in categoryModel.Listings
orderby item.Price
select item;

Resources