Create col1, col2, col3 using MVC where (1,2,3 are dynamically generated) - asp.net-mvc-3

1> .cs page
public partial class TBL_FG_MENUS
{
public string ColName1{ get; set; }
public string ColName2{ get; set; }....ntimes
public string ColValue1{ get; set; }
public string ColValue2{ get; set; }....ntimes
}
Question:
I need to loop inside view using this model
2> .cshtml page (view)
#{
int i=1;
foreach(var item in Model)
{
<p>#item.ColName+i<p><br/>
i++;
}
i=1;
foreach(var item in Model)
{
<p>#item.ColValue+i<p><br/>
i++;
}
}
Here I want ColName1, ColValue1 n times inside the loop

One possibility is to adapt your view model a little bit so that it uses 2 collections:
public partial class TBL_FG_MENUS
{
public IList<string> ColNames { get; set; }
public IList<string> ColValues { get; set; }
}
and then in your view:
#foreach(var name in Model.ColNames)
{
<p>#name</p><br/>
}
#foreach(var value in Model.ColValues)
{
<p>#value</p><br/>
}
If for some reason you cannot use collections, then the only way to achieve that is by using reflection:
#foreach(var prop in Model.GetType().GetProperties().Where(p => p.Name.StartsWith("ColName")))
{
<p>#Html.Display(prop.Name)</p><br/>
}
#foreach(var prop in Model.GetType().GetProperties().Where(p => p.Name.StartsWith("ColValue")))
{
<p>#Html.Display(prop.Name)</p><br/>
}
Obviously you should bear in mind that using reflection could have negative impact on the performance of your application and you might want to consider caching the property names used in the foreach loops to avoid querying them every time.

Related

Entity Framework: Custom proxies for POCO

I am working with the EF6 and I am a big fan of the dynamic proxies, which enables lazy loading and change tracking. Anyway I am not happy, that the lazy loading is triggered once the property is accessed instead of loading the data, when the enumerator or the count property is called first. Therefore I tried to diesable the proxys and replace them by custom proxies. It was an easy thing to use a custom object context and overload the CreateObject method. Unfortantly the ObjectMaterialized event cannot replace the entity and I am not able to replace an entity from a query. The creation of the object lies deep in internal classes of the framework.
Has anybody an idea how to use custom proxies? Or how I am able to replace the entities materialized in an object query?
You should .Include the properties you want to fetch so that you avoid an N+1 query problem.
public class User
{
public int Id { get; set; }
public string Name { get; set ;}
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Post
{
public int Id { get; set; }
public string Title { get; set ; }
public int AuthorId { get; set; }
public virtual User Author { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int Id { get; set; }
public string Note { get; set ;}
public int PostId { get; set; }
public virtual Post Post { get; set; }
public int AuthorId { get; set; }
public virtual User Author { get; set; }
}
public class BlogContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
Then this is BAD in that it'll do tons of queries:
using (var db = new BlogContext())
{
var user = db.Users.Single(u => u.Id=5)); // +1 query
foreach (var post in user.Posts) // N queries
{
var message = String.Format("{0} wrote {1}", user.Name, post.Title);
Console.WriteLine(message);
foreach (var comment in post.Comments) // N * M queries!
{
// and that .Author make N * M MORE!
var message = String.Format("\t{0} commented {1}", comment.Author.Name, comment.Note);
Console.WriteLine(message);
}
}
}
And this is GOOD in that it'll do one query:
using (var db = new BlogContext())
{
var user = db.Users
.Single(u => u.Id=5))
.Include(u => u.Posts) // eliminates the N post queries
.Include(u => u.Posts.Comments) // eliminates the M comment queries
.Include(u => u.Posts.Comments.Author); // eliminates the M comment author queries
foreach (var post in user.Posts) // N queries
{
var message = String.Format("{0} wrote {1}", user.Name, post.Title);
Console.WriteLine(message);
foreach (var comment in post.Comments) // N * M queries!
{
// and that .Author make N * M MORE!
var message = String.Format("\t{0} commented {1}", comment.Author.Name, comment.Note);
Console.WriteLine(message);
}
}
}

ASP.NET MVC 3 dropdown binding

I encountered the next indexer syntax during binding my model with collection to view.
Here is what I have:
public class CustomerModel
{
public List<Customer> Customers { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public ImportAction ImportAction { get; set; }
}
public enum ImportAction
{
Skip,
Add,
Merge
}
My view:
#using (Html.BeginForm("Edit", "Home"))
{
var index = 0;
foreach (var customer in Model.Customers)
{
<span>Name: #customer.Name</span>
#Html.DropDownListFor(x => x.Customers[index].ImportAction, customer.ImportAction.ToListItems())
index++;
}
<button type="submit">
Submit</button>
}
How to avoid this [index] usage? Any other correct syntax? Take to the look, that without it #Html.DropDownListFor would not work and update my model on post back.
you can use the loop variable 'customer' like the following:
#Html.DropDownListFor(x => customer.ImportAction)

Present multiple IEnumberables and single value properties in single webgrid

I have an Inventory Class that contains not only its own fields but several reference IDs to other classes.
public class Inventory {
public int Id { get; set; }
public string RtNum { get; set; }
public string AcntNum { get; set; }
public string CardNum { get; set; }
public string Num { get; set; }
[Range(1,3)]
public int Type { get; set; }
public int CompanyId { get; set; }
public int BranchId { get; set; }
public int PersonId { get; set; } }
In my action I generate several IEnumerable lists of the relevant fields from the other classes. I also have several non-list values I want to pass to the View. I know how to create a ViewModel to pass everything to the webgrid but have no way of iterating through the lists. I also know how to AutoMap an index to one list, see How to display row number in MVC WebGrid.
How would you combine the two so that you could use the index to iterate through multiple lists?
Update #1 (more detail)
public class Company {
public int Id { get; set; }
public string Name { get; set; } }
public class Branch {
public int Id { get; set; }
public string Name { get; set; } }
public class Person {
public int Id { get; set; }
public string Name { get; set; } }
public class MyViewModel {
public int PageNumber { get; set; }
public int TotalRows { get; set; }
public int PageSize { get; set; }
public IEnumerable<Inventory> Inventories { get; set; }
public int Index { get; set; }
public IEnumerable<string> CmpNm { get; set; }
public IEnumerable<string> BrnNm { get; set; }
public IEnumerable<string> PrnNm { get; set; } }
Controller
public class InventoryController : Controller
{ // I have a paged gird who’s code is not relevant to this discussion but a pagenumber,
// pagesize and totalrows will be generated
private ProjectContext _db = new ProjectContext();
public ActionResult Index() {
IEnumerable<Inventory> inventories = _db.Inventories;
List<string> cmpNm = new List<string>; List<string> brnNm = new List<string>; List<string> prnNm = new List<string>;
foreach (var item in inventories) { string x1 = "";
Company cmps = _db. Company.SingleOrDefault(i => i.Id == item.CompanyId); if (cmps!= null)
{ x1 = cmps.Name; } cmpNm.Add(x1); x1 = "";
Branch brns = _db. Branch.SingleOrDefault(i => i.Id == item. Branch Id); if (brns!= null) { x1 = brns.Name; } brnNm.Add(x1); x1 = "";
Person pers = _db.Persons.SingleOrDefault(i => i.Id == item. PersonId);
if (pers!= null) { x1 = pers.Name; } prnNm.Add(x1);
// the MyViewModel now needs to populated with all its properties and generate an index
// something along the line of
new MyViewModel { PageNumber= pagenumber, PageSize= pagesize, TotalRows=Totalrows, Inventories = inventories; CmpNm=cmpNm, BrnNm=brnNm, PrnNm=prnNm}
View (How to create the Index is the problem)
#model.Project.ViewModels.MyViewModel
#{ var grid = new WebGrid(Model.Inventories, Model.TotalRows, rowsPerPage: Model.PageSize); }
#grid.GetHtml( columns: grid.Columns(
Grid.Column(“PrnNm”, header: "Person", format: #Model.PrnNm.ElementAt(Index))
Grid.Column(“BrnNm”, header: "Branch", format: #Model.BrnNm.ElementAt(Index))
Grid.Column(“CmpNm”, header: "Company", format: #Model.CmpNm.ElementAt(Index))
grid.Column("RtNum", header: "Route"),
grid.Column("AcntNum", header: "Account"),
grid.Column("CardNum", header: "Card")
… ) )
What the grid should look like is self-evident.
It's pretty unclear what is your goal. But no matter what it is I would recommend you to define a real view model reflecting the requirements of your view and containing only the information you are interested in seeing in this grid:
public class InventoryViewModel
{
public int Id { get; set; }
public string PersonName { get; set; }
public string BranchName { get; set; }
public string CompanyName { get; set; }
public string RouteNumber { get; set; }
public string AccountNumber { get; set; }
public string CardNumber { get; set; }
}
Now you could have the main view model:
public class MyViewModel
{
public int PageNumber { get; set; }
public int TotalRows { get; set; }
public IEnumerable<InventoryViewModel> Inventories { get; set; }
}
Alright, the view is now obvious:
#model MyViewModel
#{
var grid = new WebGrid(
Model.Inventories,
rowsPerPage: Model.PageSize
);
}
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Id", header: "Inventory id"),
grid.Column("PersonName", header: "Person"),
grid.Column("BranchName", header: "Branch"),
grid.Column("CompanyName", header: "Company"),
grid.Column("RouteNumber", header: "Route"),
grid.Column("AccountNumber", header: "Account"),
grid.Column("CardNumber", header: "Card")
)
)
Now all that's left is build this view model in your controller. Since I don't know what you are trying to achieve here, whether you need an inner join or a left outer join on those columns, I will take as an example here a left outer join:
public ActionResult Index()
{
var inventories =
from inventory in _db.Inventories
join person in _db.Persons on inventory.PersonId equals person.Id into outerPerson
join company in _db.Companies on inventory.CompanyId equals company.Id into outerCompany
join branch in _db.Branch on inventory.BranchId equals branch.Id into outerBranch
from p in outerPerson.DefaultIfEmpty()
from c in outerCompany.DefaultIfEmpty()
from b in outerBranch.DefaultIfEmpty()
select new InventoryViewModel
{
PersonName = (p == null) ? string.Empty : p.Name,
CompanyName = (c == null) ? string.Empty : c.Name,
BranchName = (b == null) ? string.Empty : b.Name,
Id = inventory.Id,
AccountNumber = inventory.AcntNum,
CardNumber = inventory.CardNum,
RouteNumber = inventory.RtNum
};
var model = new MyViewModel
{
PageSize = 5,
// TODO: paging
Inventories = inventories.ToList()
};
return View(model);
}
And that's pretty much it. Of course in this example I am leaving the pagination of the Inventories collection for you. It should be pretty trivial now to .Skip() and .Take() the number of records you need.
As you can see ASP.NET MVC is extremely simple. You define a view model to reflect the exact requirements of what you need to show in the view and then populate this view model in the controller. Most people avoid view models because they fail to populate them, probably due to lack of knowledge of the underlying data access technology they are using. As you can see in this example the difficulty doesn't lie in ASP.NET MVC at all. It lies in the LINQ query. But LINQ has strictly nothing to do with MVC. It is something that should be learned apart from MVC. When you are doing MVC always think in terms of view models and what information you need to present to the user. Don't think in terms of what you have in your database or wherever this information should come from.

ASP.Net MVC 3 Multiple CheckBoxLists

I am developing an ASP.Net MVC 3 Web application and I recently posted a question about how to display a checkboxlist
ASP.Net MVC 3 Retrieve Checkbox List Values
and thanks to the help from RubbleFord and Darin Dimitrov I was able to get this working.
This works nicely for one checkboxlist, however, I now need to be able to display several checkboxlists on the same View, ie, see image attached.
The ViewModels I use to currently display one list are as follows;
public class ViewModelShiftSubSpecialties
{
public ListItem specialtyName { get; set; }
public IEnumerable<ViewModelCheckBox> SubSpecialityList { get; set; }
}
public class ViewModelCheckBox
{
public string Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
And within my Controller I populate ViewModelShiftSubSpecialties like so:
var subSpecialties = GetSubSpecialtiesForSpecialty(5);
ViewModelShiftSubSpecialties viewModel = new ViewModelShiftSubSpecialties();
var checkBoxList = new List<ViewModelCheckBox>();
viewModel.specialtyName = _listService.GetListItemByID(5); //Medicine Specialty
foreach (var item in subSpecialties)
{
ViewModelCheckBox chkBox = new ViewModelCheckBox { Id = item.subID.ToString(), Name = item.ListSub.description, Checked = false };
checkBoxList.Add(chkBox);
}
viewModel.SubSpecialityList = checkBoxList;
In my View, I display the list name and also use an Editor template to display the checkboxlist
<h3>#Model.specialtyName.description</h3>
#Html.EditorFor(m => m.SubSpecialityList)
However, I am totally stumped as how to get the above code to work with multiple checkboxlists on one View. Is this even possible?
I would really appreciate if someone could please help me with this.
Thanks.
It looks like you've done all the work already. You already have an Editor Template that works correctly with a ViewModelCheckBox IEnumerable. Editor templates wouldn't be useful if you couldn't reuse them for the same datatype. You just need to use it three times. Just extend your ViewModel
public class ViewModelShiftSubSpecialties
{
public ListItem specialtyName { get; set; } //Might need 3 of these
public IEnumerable<ViewModelCheckBox> SubSpecialityList1 { get; set; }
public IEnumerable<ViewModelCheckBox> SubSpecialityList2 { get; set; }
public IEnumerable<ViewModelCheckBox> SubSpecialityList3 { get; set; }
}
Create all three in your controller (and give them better names then I did).
And then in your View
#Html.EditorFor(m => m.SubSpecialityList1)
#Html.EditorFor(m => m.SubSpecialityList2)
#Html.EditorFor(m => m.SubSpecialityList3)
Alternatively you could create a class that contains a single specialty name and IEnumerable ViewModelCheckBox, and have your ViewModel have an IEnumerable of this new class. Then create a new Editor Template for this new class. I think this is worth it if your list size is variable/ might change. Otherwise I'd use the earlier solution for a simple fix.
public class ViewModelShiftSubSpecialties
{
public class IEnumerable<SubSpecialty> { get; set; }
}
public class SubSpecialty
{
public ListItem specialtyName { get; set; }
public IEnumerable<ViewModelCheckBox> SubSpecialityList
}

MVC3 Dynamic DataAnnotation attribute StringLength

UPDATE #3: Entire question
I have a class HB:
public class HB
{
public int Id { get; set; }
[StringLength(3000)]
public string Text { get; set; }
public Title Title { get; set; }
}
And Title:
public class Title
{
public int Id { get; set; }
public string Name { get; set; }
public int MaxChar { get; set; }
}
Before you can write a HB (which is kind of an article), you have to choose your title, so your StringLength for HB.Text can be determined. Meaning, this article can only have a certain amount of chars, deppending on what 'Title' the writer has. Example: Title1 can only write a 'HB' with 1000 chars, and Title2 can write a 'HB' with 3000 chars. So. Thats means the the StringLength has to come from Title.MaxChar. Whats the smartest way to do that?
The Title entity is prefixed data that will be stored in the db.
To be crystal clear, what I want to achieve is something in the line with: [StringLength(Title.MaxChar)]
Ive done structure/design for this mechanism in Webforms a million times, my brain just cant addapt to mvc, so some help would be appreciated. Code would be even more appreciated.
Pretty sure that is not possible as written. This strikes me as trying to force business logic into the model that belongs in the controller.
In this situation, I would make the attribute on the Text property [StringLength(3000)]. In the controller, during validation, I would write something along these lines:
public ActionResult (HB model)
{
if (model.Text.Length > model.Title.MaxChar){
ModelState.AddModelError("Text", string.Format("Text for this Title cannot exceed {0} characters.", model.Title.MaxChar));
}
if (ModelState.IsValid)
{
//do stuff
return RedirectToAction("Index"); //or something
}
else
{
return View(model);
}
}
I believe this will accomplish what you are trying to do. Now, for the Title object, I'd flatten that out a bit in your model:
public class HB
{
#region Base Properties
public int Id { get; set; }
[StringLength(3000)]
public string Text { get; set; }
#endregion
#region Title Properties
public int TitleId { get; set; }
public string TitleName { get; set; }
public int TitleMaxChar { get; set; }
#endregion
}
This is assuming you need to display that information in your view. If you just need to reference it for your business logic validation, just have the TitleId property and use that to instantiate the Title object in your controller when you need it. Don't forget to make hidden inputs for each of these properties if they are not editable!

Resources