|
|
The simplest option would be to deserialize as a Dictionary(Of String, clsThings) . If necessary, you can then ignore the keys, and just read the values.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
i am fetching data from db using EF. when i fetching then i am filtering and sorting data too.this way i am sorting by column name. huge line i have to write which looks not good.
switch (SortColumn)
{
case "CompanyName":
ViewBag.OldSort = "CompanyName";
if (SortColumn.Equals(CurrentSort))
{
customer = customer.OrderByDescending(m => m.CompanyName);
ViewBag.CurrentSort = "";
ViewBag.SortOrder = "desc";
}
else
{
customer = customer.OrderBy(m => m.CompanyName);
ViewBag.SortOrder = "asc";
}
break;
case "ContactName":
ViewBag.OldSort = "ContactName";
if (SortColumn.Equals(CurrentSort))
{
customer = customer.OrderByDescending(m => m.ContactName);
ViewBag.CurrentSort = "";
ViewBag.SortOrder = "desc";
}
else
{
customer = customer.OrderBy(m => m.ContactName);
ViewBag.SortOrder = "asc";
}
break;
case "ContactTitle":
ViewBag.OldSort = "ContactTitle";
if (SortColumn.Equals(CurrentSort))
{
customer = customer.OrderByDescending(m => m.ContactTitle);
ViewBag.CurrentSort = "";
ViewBag.SortOrder = "desc";
}
else
{
customer = customer.OrderBy(m => m.ContactTitle);
ViewBag.SortOrder = "asc";
}
break;
case "Address":
ViewBag.OldSort = "Address";
if (SortColumn.Equals(CurrentSort))
{
customer = customer.OrderByDescending(m => m.Address);
ViewBag.CurrentSort = "";
ViewBag.SortOrder = "desc";
}
else
{
customer = customer.OrderBy(m => m.Address);
ViewBag.SortOrder = "asc";
}
break;
case "Default":
ViewBag.OldSort = "CompanyName";
customer = customer.OrderBy(m => m.CompanyName);
ViewBag.SortOrder = "asc";
break;
}
please see for 4 columns i have to write so many line of code. suppose if i need to work with 40 columns then how many more line i need to write. so tell me best option to minimize the code for sorting when working with EF.
|
|
|
|
|
Assuming all of your sortable columns are strings:
private static readonly IReadOnlyDictionary<string, Expression<Func<Customer, string>>> SortColumns = new Dictionary<string, Expression<Func<Customer, string>>>
{
["CompanyName"] = c => c.CompanyName,
["ContactName"] = c => c.ContactName,
["ContactTitle"] = c => c.ContactTitle,
["Address"] = c => c.Address,
};
...
if (SortColumns.TryGetValue(SortColumn, out var sortProperty))
{
ViewBag.OldSort = SortColumn;
if (SortColumn.Equals(CurrentSort))
{
customer = customer.OrderByDescending(sortProperty);
ViewBag.CurrentSort = "";
ViewBag.SortOrder = "desc";
}
else
{
customer = customer.OrderBy(sortProperty);
ViewBag.SortOrder = "asc";
}
}
else
{
customer = customer.OrderBy(c => c.CompanyName);
ViewBag.OldSort = "CompanyName";
ViewBag.SortOrder = "asc";
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you sir, you said Assuming all of your sortable columns are strings: so if few columns are type of datetime, int or double then your above code will not work?
please suggest what to add in your code if few columns are type of datetime, int or double.
i will test your code let you know the status.
Thanks
|
|
|
|
|
That gets slightly more complicated.
Start by adding the necessary using directives:
using System.Linq;
using System.Linq.Expressions;
Next, you'll need a method to sort based on a LambdaExpression :
private static IOrderedQueryable<TSource> OrderBy<TSource>(IQueryable<TSource> source, LambdaExpression keySelector, bool descending)
{
string methodName = descending ? "OrderByDescending" : "OrderBy";
Type[] typeArguments = { typeof(TSource), keySelector.ReturnType };
var query = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, keySelector);
return (IOrderedQueryable<TSource>)source.Provider.CreateQuery<TSource>(query);
}
Then you'll need to update the dictionary to store LambdaExpression values. To do that cleanly, you'll need a helper method to convert an anonymous delegate to a LambdaExpression :
private static LambdaExpression Expr<TProperty>(Expression<Func<Customer, TProperty>> fn) => fn;
private static readonly IReadOnlyDictionary<string, LambdaExpression> SortColumns = new Dictionary<string, LambdaExpression>
{
["CompanyName"] = Expr(c => c.CompanyName),
["ContactName"] = Expr(c => c.ContactName),
["ContactTitle"] = Expr(c => c.ContactTitle),
["Address"] = Expr(c => c.Address),
};
And finally, update your sorting code to use the new method:
if (SortColumns.TryGetValue(SortColumn, out var keySelector))
{
ViewBag.OldSort = SortColumn;
if (SortColumn.Equals(CurrentSort))
{
customer = OrderBy(customer, keySelector, true);
ViewBag.CurrentSort = "";
ViewBag.SortOrder = "desc";
}
else
{
customer = OrderBy(customer, keySelector, false);
ViewBag.SortOrder = "asc";
}
}
else
{
customer = customer.OrderBy(c => c.CompanyName);
ViewBag.OldSort = "CompanyName";
ViewBag.SortOrder = "asc";
}
Now you can sort by any property type.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thanks a lot sir
your 2nd posted code will work with any data type ?
|
|
|
|
|
It will work with any type that would work with a manual customers.OrderBy(c => c.SomeProperty) call.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
i am curious to know any free health monitoring dashboard exist for asp.net webform or mvc project which we can use it.
i search google and found one for asp.net core ASP.NET Core Real-time Performance Monitoring – Allan Hardy[^]
so please check my link and tell me anything such exist for asp.net webform or mvc4/5 project.
thanks
|
|
|
|
|
|
Hello, I am a Very New programmer in the MVC architecture and I am struggling with getting data from my controller to my view. I am in my last year of college and we are building a web application for a non profit organization that will track residents in their facility.
I am trying to query the database for the rooms table and select the rooms that have the IsOccupied field set to false.
Then I am filtering the returned query for a range of rooms and putting them in Wings and passing them to the view.
My struggles are with getting the room object from the controller to the view. Then in the view, burrowing down into the object and getting the room number out and displaying it.
Currently I have the following in my class.
public class Room
{
public int RoomID { get; set; }
[Display(Name = "Room Number")]
public int RoomNum { get; set; }
[Display(Name = "Is Occupied")]
public bool IsOccupied { get; set; }
}
My Controller code is:
public ActionResult Create()
{
//Query database for IsOccupied flag//
var AvailRoom = from s in db.Rooms
.Where(s => s.IsOccupied == false)
select s;
foreach (var room in AvailRoom)
{
if (room.RoomNum > 101 && room.RoomNum < 126)
{
IEnumerable<selectlistitem> EastSouth = new SelectList(room.RoomNum.ToString());
ViewBag.EastSouth = EastSouth;
}
}
My view code is:
@Html.Label("Available Rooms")
@Html.DropDownList("EastSouth")
Currently all I get when I compile is a dropdown box with 1, 2 and 5.
I am stumped. Any recommendations on where to go from here would be really appreciated.
|
|
|
|
|
You're looping through the rooms, but you're overwriting the EastSouth list each time.
You're also passing a string as the only parameter to the SelectList constructor. This will call the SelectList(IEnumerable)[^] overload, which will create a list item for each character in the string.
Change your code to pass the list of rooms to the SelectList constructor, along with the name of the property which contains the value and the text:
var AvailRoom = db.Rooms
.Where(s => s.IsOccupied == false)
.Where(s => s.RoomNum > 101 && s.RoomNum < 126)
;
ViewBag.EastSouth = new SelectList(AvailRoom, "RoomNum", "RoomNum");
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
First off, I would like to apologize for my horrible code!!!! I reread my post and I am really embarrassed. But I guess it takes making a fool out of yourself to get better.
Thank you for your help. This worked like a champ.
|
|
|
|
|
i have creating url using routelink.
@Html.RouteLink("Edit", "PageWithId",
new
{
controller = "Customers",
action = "Edit",
id = item.CustomerID,
page = ViewBag.CurrentPage
})
i am using this routing PageWithId with route link
routes.MapRoute(
name: "PageWithId",
url: "{controller}/{action}/{page}/{id}",
defaults: new { controller = "Customers", action = "Edit", page = UrlParameter.Optional, id = UrlParameter.Optional }
);
i have 3 routing code in route.config file. here is all
routes.MapRoute(
name: "PageWithSort",
url: "{controller}/{action}/{page}/{SortColumn}/{CurrentSort}",
defaults: new { action = "Index", page = UrlParameter.Optional, SortColumn = UrlParameter.Optional, CurrentSort = UrlParameter.Optional }
);
routes.MapRoute(
name: "PageWithId",
url: "{controller}/{action}/{page}/{id}",
defaults: new { controller = "Customers", action = "Edit", page = UrlParameter.Optional, id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
when i run my program the route link generate url like http://localhost:55831/Customers/Edit/1/ALFKI
when i click on the link the Edit action is getting called but customer id is getting null where as ALFKI is there in url as customer id.
here is my edit action details
public ActionResult Edit(string id, int page)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
ViewBag.CurrentPage = page;
return View(customer);
}
please tell me why id is getting null when ALFKI as passing as customer id?
thanks
|
|
|
|
|
The URL /Customers/Edit/1/ALFKI matches both the PageWithSort and PageWithId routes. As a result, the first matching route will be selected - PageWithSort - and the ALFKI string will be available as a parameter called SortColumn .
Since your action doesn't take a parameter called SortColumn , and the route doesn't contain any data for a parameter called id , the parameter will be set to null .
You can see this for yourself using the ASP.NET Routing Debugger[^] package.
You'll need to rename the parameters on your actions so that they match the parameters in the route. Since the PageWithSort route will match anything that the other two routes would, that's the one you need to match.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thank you sir....have a nice day 
|
|
|
|
|
HI,
suppose i am inserting new records in db and PK field may be identity type of may not. i am showing 10 records per page through skip() and take(). now how could i calculate page no where newly inserted record will appear.
give me some direction. thanks
|
|
|
|
|
It depends on many factors, such as indexing, sort order, etc.
The rest of it is clear mathematics.
|
|
|
|
|
i have seen a example of asp.net mvc routing code where two controller name has been referenced.
routes.MapRoute(
name: "test",
url: "{controller}/{action}/{page}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new { action = "Index" }
);
just started working with asp.net mvc. so curious to know that what is the objective to mention controller or action name twice ?
in above example there is two defaults....when and why it is required.
just requesting anyone can explain the same with a nice example. thanks in advance
|
|
|
|
|
I don't know where you got that example from, but it's not valid C#. Not only are you missing a comma between the last two parameters, but you've specified the same named parameter twice.
Try to compile that code, and you'll get:
CS1740 Named argument 'defaults' cannot be specified multiple times
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
HI Sir,
please check this url asp.net mvc 4 - Using Url.RouteUrl() with Route Names in an Area - Stack Overflow[^]
in the above url you will see a example where two controller name has been mentioned.
here a small snippet.
context.MapRoute(
"UserHome",
"User/{id}",
new { action = "Index", controller = "Home", area = "User", id = 0,
httproute = true },
new { controller = @"Home", id = @"\d+" }
);
looking for your further guidance. thanks
|
|
|
|
|
That doesn't match the code in your question.
This code is calling the MapRoute(name, url, defaults, constraints)[^] overload. The second anonymous object represents the constrains on the route.
See: ASP.NET Routing: Adding Constraints to Routes[^]
It would probably be worth reading most of that article. (You can ignore the "Web Forms" section.)
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
sir can you give some direction that which area i need to fix in my code.
|
|
|
|
|
What code? You've shown two different code blocks, one of which won't compile. And you haven't described a problem that needs fixing with either one.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|