MVC5 route to different Controller's Action/View - asp.net-mvc

I have a MVC application for users to make requests, database schema something like this:
Request(RequestID, RequestType,...)
CarKey(CarKeyID, RequestID,...)
DoorKey(DoorKeyID, RequestID,...)
CarKey and DoorKey are different request types.
Let's say I have one CardKey request with a RequestID = 10, CarKeyID = 3, one DoorKey request with a RequestID = 11 and DoorKeyID = 4
My search result page shows all the requests with links like this:
http://localhost/Requests/10
When user click on this link, since it's a CarKey request, how do I route it to my CarKey controller's Edit action with RequestID = 10 or CarKeyID = 3 ?

After doing some research, I found this is very useful:
RedirectToAction with parameter
So What I did was to change return type in my RequestsController's Details action to
var carKeyID = request.CarKeys.First().CarKeyID;
return RedirectToAction("Edit","CarKeys", new { id = carKeyID});

Related

Calling multiple list of item in View using Tuple in MVC

When i am using 4 List at view then its working properly means in my example if i am using till PreClearanceDetail its working properly for all four list but after 5th one added that is FAQ its showing below compliation error.
Kindly guide for the same because as per my knowledge tuple can take N number of arguments.
My controller code is :
[HttpGet]
public ActionResult AdminDashboard()
{
DB_Entities entities = new DB_Entities();
List<Menu> MenuVM= entities.Menu.ToList();
List<TradeClose> tradeclose = entities.TradeCloses.ToList();
List<NonComplianceCas> cases = entities.NonComplianceCases.ToList();
List<PreClearanceDetail> data = entities.PreClearanceDetails.Where(a => a.Flag == ull).ToList();
List<FAQ> faqs = entities.FAQs.ToList();
List<Annoucement> Annoucements = entities.Annoucements.ToList();
return View(Tuple.Create(Menu, tradeclose, cases, data , faqs));
}
My View code is :
#model Tuple<List<MenuVM>, List<TradeClose>, List<NonComplianceCas>, List<PreClearanceDetail> ,List<FAQ>>

Getting data back on Html.ListBoxFor post in MVC

It seems all the examples I can find use a ViewModel for some reason, so a MVC and not MVVM answer is what I'm looking for :)
Controller
List<PermOptions> have = new List<PermOptions>();
List<PermOptions> nothave = new List<PermOptions>();
...populate the lists here...
var set = new PermissionSet
{
ExtId = extid,
HaveList = have,
NotHaveList = nothave
};
return View(set);
View
#model path.to.model.PermissionSet
#{
var NotHave = new MultiSelectList(Model.NotHaveList, "Id", "Role");
}
#Html.ListBoxFor(model => model.NotHaveList, NotHave, new { #size = "30", id = "possible" });
#{
var Have = new MultiSelectList(#Model.HaveList, "Id", "Role");
}
#Html.ListBoxFor(model => model.HaveList, Have, new { #size = "30", id = "have" });
Everything works just fine displaying the initial lists and moving items, but when I submit the form the ListBoxFors are part of to the Post action, PermissionSet.HaveList and PermissionSet.NotHaveList are empty with a zero count. Thinking it was a select issue or format of return issue, I added javascript to select all the items in both boxes, and in the browser debug pane I can see that there are values in the submitted Form data that match up to various option values for NotHave and Have, but if in the Post action, I make a call to ViewData["NotHave"], it is also reporting empty.
What do I need to do to get the list of items in each ListBoxFor in my Post controller, preferrably as part of PermissionSet?

How to read cookie in view MVC3?

I have a list of comment objects in the view. Each comment has one cookie that mark the status from user action. Example: like, spam,...
In the view, I want to read the corresponding cookie of each comment to display the right view to user. Example: user A who liked comment B then the view will display the unlike button
I don't want to read cookie in the controller because the return data is a list of comment objects.
My question is how to read cookie directly in view of MVC3?
In razor view within #{ } block use below code.
string val = "";
if (Request.Cookies["CookieName"] != null) {
val = Request.Cookies["CookieName"].Value;
}
for Read Cookie:
var cookie = Request.Cookies["Key"];
ViewBag.MyCookie= int.Parse(cookie);
and show it in view As:
#ViewBag.MyCookie;
use Request.Cookies
string val = Request.Cookies["CookieName"]?.Value;

JQGrid Loading lots of data

SITUATION
I am using Trirand JQGrid for MVC[server side] in my proj.
I've got more than 5 hundred thousand records in a single table.
I load the data by calling this piece of code. this is what gives 500000 records collection.
IEnumerable<myIndexViewModel> myviewmodel= _allincidents.Select(x => new myIndexViewModel
{
IncidentRequestStatus = x.RequestStatus,
RequestByUserName = x.RequestByUserName,
Subject = x.Subject
});
gridModel.JqGrid.DataBind(myviewmodel.AsQueryable());
JQgrid handles the json based ajax requests very nicely for every next page i click.
PROBLEM
I dont want to load 5 hundred thousand records all together on the page load event as it kills jqgrid.
If i write a stored procedure in the DB for requesting a specific page to be displayed then its gonna load only that page in the myviewmodel collection.
How do i get pages on the fly from the DB when the next page is clicked. is this even possible in jqgrid?
SITUATION 2
Based on the answers from VIJAY and MARK the approach they have shown is absolutely correct but over here the JQGRID for MVC sets up the DATAURL property for making the method call. In this case its the IncidentGridRequest.
How do i send in the page number when the grid next page or previous page is clicked?
incidentModel.IncidentGrid.DataUrl = Url.Action("IncidentGridRequest")
public JsonResult IncidentGridRequest()
{
}
Your controller action that will provide your grid with results can accept some extra information from jqGrid.
public ActionResult GetGridData(string sidx, string sord, int page, int rows, bool _search, string filters)
The main parts you are interested in is the page, rows (sidx is for column sorting, sord for the sorting order, _search if there was a search done on the grid, and if so filters contains the search information)
When you generate your results you should be able to then
IEnumerable<myIndexViewModel> myviewmodel = allincidents.Select(x => new myIndexViewModel
{
IncidentRequestStatus = x.RequestStatus,
RequestByUserName = x.RequestByUserName,
Subject = x.Subject
}).Skip((page - 1) * rows).Take(rows)
PS. I'm not sure if you using IEnumberable will be moving a large amount of data from your DB but you might want to use IQueryable when you generate this subset of data for the jqGrid.
Edit: To deal with your paging issues, You should be calculating the number of total records in your query and passing that value to the grid, Ex
int totalRecords = myviewmodel.Count();
and then later you would pass that to your grid as a jSon value. Ex
var jsonData = new
{
total = (totalRecords + rows - 1) / rows,
page = page,
records = totalRecords,
userdata = new {SearchResultsFound = searchResultsFound},
rows = (
......
Yes, for example if you are accepting the page number you want to turn to in a variable named page and the have the size of page in a variable pageSize then:
IEnumerable<myIndexViewModel> myviewmodel = allincidents.Select(x => new myIndexViewModel
{
IncidentRequestStatus = x.RequestStatus,
RequestByUserName = x.RequestByUserName,
Subject = x.Subject
}).Skip((page-1)*pageSize).Take(pageSize));
will give you the records of size pageSize to you.
The Trirand jqGrid for ASP.NET MVC is using IQueryable interface inside the JqGrid.DataBind() method to implement pagin, sorting and filtering.
So the key here is to use datasource, which handle these types of operations at the database level (by crafting SQL queries to the database in such a way that only the data required is fetched). All major ORMs have this support, this includes: LINQ-2-SQL, Entity Framework, NHbiernate, LLBLGen.
You just need to use one of this technologies, and past the required context directly to JqGrid.DataBind() method (without extracting the data manually like you do it in your sample).
An easier approach by using PagedList library (from Nuget). There is a useful blog by Joseph Schrag
public JsonResult Users(int PageNo, int Rows)
{
var UserList = db.Users.Select(t => new
{
t.UserId,
t.Username,
t.Firstname,
t.Lastname,
t.Designation,
t.Country,
t.Email
}).OrderBy(t => t.UserId);
var pagedUserList = UserList.ToPagedList(PageNo, Rows);
var results = new
{
total = pagedUserList.PageCount, //number of pages
page = pagedUserList.PageNumber, //current page
records = UserList.Count(), //total items
rows = pagedUserList
};
return new JsonResult() { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Ways to define an ASP.NET MVC Route

I was wondering if you could show me all the various ways to declare routes in ASP.NET MVC (1 and 2). Please explain each method of defining a route, how it is used, and what case it covers.
Here is an example of what I am hoping to collect here:
routes.MapRoute("Directors",
"Directors/{filter}/{skip}",
new { controller = "Directors", action = "Index", skip = 0, filter = "" },
new { skip = #"\d+", filter = #"^[a-zA-Z]+.+" });
Directors = the name of the route. Directors/{filter}/{skip} = the url definition. new { controller = "Directors", action = "Index", skip = 0, filter = "" } = the default for this route. new { skip = #"\d+", filter = #"^[a-zA-Z]+.+" } = the constraints for this route.
My first port of call would be the ASP.NET learning pages on routing.
I think this may also be a good use of the Community Wiki feature, as the question you're asking a pretty vague question where there are not real answers, just good documentation on routes.

Resources