Add comment - two model in one view - asp.net-mvc

I would like to add two model in one view: CommentVM and BlogVM.
CommentVM - comments,
BlogVM - postDetails.
I try to add comment via ajax to my databse and than pass my two model in to view. But when I try to display my page I received error that my object is null (commentVM)
below code my controller
Any sugestion what I am doing wrong?
Thank for your help!
// GET: Admin/Blog/kategoria/{name}/post/id
[ActionName("post")]
public ActionResult PostDetails(int id)
{
//Declare BlogVM
BlogVM model;
CommentVM model2;
int id2;
using (Db db = new Db())
{
//Get the page
BlogDTO dto = db.Blog.Find(id);
//Confirm page exist
if (dto == null)
{
return Content("Taka strona nie istnieje!");
}
//Init BlogVM
model = new BlogVM(dto);
id2 = dto.Id;
// CommentDTO dto2 = db.Comments.Find(x => x.PostId == id2);
model2 = new CommentVM();
}
var finalItem = new DetailsComment
{
Blog = model,
Comment = model2
};
return View("PostDetails", finalItem);
}
code my models:
public class CommentVM
{
public CommentVM()
{
}
public CommentVM(CommentDTO row)
{
Id = row.Id;
Name = row.Name;
Body = row.Body;
PostId = row.PostId;
CreatedAt = row.CreatedAt;
}
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Body { get; set; }
public int PostId { get; set; }
public DateTime CreatedAt { get; set; }
//public IEnumerable<CommentVM> CommentDetails { get; set; }
}
public class BlogVM
{
public BlogVM()
{
}
public BlogVM(BlogDTO row)
{
Id = row.Id;
Title = row.Title;
Slug = row.Slug;
Body = row.Body;
CategoryName = row.CategoryName;
CategoryId = row.CategoryId;
CreatedAt = row.CreatedAt;
Sorting = row.Sorting;
HasSidebar = row.HasSidebar;
}
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 3)]
public string Title { get; set; }
public string Slug { get; set; }
[Required]
[StringLength(int.MaxValue, MinimumLength = 3)]
[AllowHtml]
public string Body { get; set; }
public string CategoryName { get; set; }
[Required]
public int CategoryId { get; set; }
public DateTime CreatedAt { get; set; }
public int Sorting { get; set; }
public bool HasSidebar { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
public class DetailsComment
{
public BlogVM Blog { get; set; }
public CommentVM Comment { get; set; }
public IEnumerable<CommentVM> CommentDetails { get; set; }
}
In my view
#foreach (var item in Model.CommentDetails)
{
<tr>
<td>
<div class="ajaxdivtd"></div>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Body)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedAt)
</td>
</tr>
}

If, according to your comments, you have multiple comments per post, then here's what you need to do:
//Declare BlogVM
BlogVM model;
CommentVM model2; //you can probably get rid of this variable since you want multiple comments per post, rather than a single one, but that's up to you
List<CommentVM> commentsModel; //new List object to hold the multiple comments for the post
and:
id2 = dto.Id;
var dto2 = db.Comments.Find(x => x.PostId == id2);
//Convert dto2 from an list/enumerable of CommentDTO to a List<CommentVM>, perhaps via AutoMapper (or other such utility), or even manually via a foreach
commentsModel = YourConversionMethod(dto2);
finally:
var finalItem = new DetailsComment
{
Blog = model,
Comment = model2,
CommentDetails = commentsModel
};

Related

how to write method for mapping lists in viewmodel and display collection in razor view

I am trying to display a collection of all products (using a view model) in my Pro() method
Models
public class Product
{
public Product() { this.AddDate = DateTime.Now; }
public int ProductId { get; set; }
[Required(ErrorMessage = "Enter Product name")]
[StringLength(160)]
public string ProductName { get; set; }
[Required(ErrorMessage = "Enter Product Description")]
[StringLength(500)]
public string ProductDescription { get; set; }
public DateTime AddDate { get ; private set; }
[Required(ErrorMessage = "Select Category")]
[Display(Name="Category")]
public string Category { get; set; }
[Required(ErrorMessage = "Location")]
public bool location { get; set; }
}
public class ProductPicture
{
public int id { get; set; }
public int ProductId { get; set; }
[Required(ErrorMessage ="Please Select Picture")]
public string pictureurl { get; set; }
}
View model
public class ProductViewModel
{
public int ProductId { get; set; }
public string ProductName { get; set; }
[Required(ErrorMessage = "Enter Product Description")]
[StringLength(500)]
public string ProductDescription { get; set; }
public DateTime AddDate { get; private set; }
[Required(ErrorMessage = "Select Category")]
[Display(Name = "Category")]
public string Category { get; set; }
[Required(ErrorMessage = "Location")]
public bool location { get; set; }
public IEnumerable<ProductPicture> ProductPictures { get; set; }
}
Controller method
public ActionResult pro()
{
ProductViewModel product = new ProductViewModel();
var pro = db.Products.ToList();
if (pro != null)
{
product.ProductName = pro.ProductName;
product.ProductDescription = pro.ProductDescription;
product.Payextra = pro.Payextra;
product.location = pro.location;
product.ProductPictures = db.ProductPictures.Where(m => m.ProductId == pro.Select(m=>m.ProductId));
}
return View(product);
}
Currently this is throwing the following exception
since i am trying to map complete list with a single object "=" operator can not be applied to int to IEnumerable. logically i am doing something wrong , so please help me to select current id from IEnumerable and map with current productpicture list and at last create the collection of same viewmodel which can be displayed in view.
You need to change the method to project the collection of Product to a collection of ProductViewModel and return that to the view.
public ActionResult Pro()
{
var pictures = db.ProductPictures;
var model = db.Products.Select(p => new ProductViewModel
{
ProductName = p.ProductName,
ProductDescription = p.ProductDescription,
....
ProductPictures = pictures.Where(x => x.ProductId == p.ID)
};
return View(model);
}
Then in the view
#model IEnmerable<ProductViewModel>
<table>
<thead>
<tr>
<th>#Html.DisplayNameFor(m => m.ProductName)</th>
....
</tr>
</thead>
<tbody>
#foreach(var product in Model)
{
<tr>
<td>#Html.DisplayFor(m => product.ProductName)</td>
....
Side note: I recommend you change the name of the method to Index() which means a user can navigate to it using .../Products (assuming your using the default routing), or at least to a name that indicates your displaying all products (the current url will be ../Products/Pro which does not convey any useful meaning to a user)

MVC ASP.net Multiple Views trying to store tags

Model:
public class PublishedSongViewModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
public string SongName { get; set; }
//...
[Required]
public IEnumerable<string> Category { get; set; }
}
public class CategoryViewModel
{
public short Id { get; set; }
public string Title { get; set; }
public virtual ICollection<SongCategoryViewModel> SongCategory { get; set; }
}
public class SongCategoryViewModel
{
public int Id { get; set; }
[Required]
public int PublishedSongId { get; set; }
[Required]
public short CategoryId { get; set; }
}
View:
#model IList<PublishedSongViewModel>
#using (Html.BeginForm("PublishMusic", "Publish", FormMethod.Post, new { #enctype = "multipart/form-data", #id = "form-upload" }))
{
#Html.DropDownListFor(x => Model[i].Category, new SelectList(//Categories list here), new { #class = "form-control dl_Categories ", Multiple = "Multiple" })
}
Controller:
[HttpPost]
public ActionResult PublishMusic(IEnumerable<PublishedSongViewModel> songDetails)
{
if (songDetails != null)
{
IEnumerable<PublishedSongViewModel> savedSongs = (IEnumerable<PublishedSongViewModel>)(Session["UserSongs"]);
var lookupDetails = songDetails.ToDictionary(song => song.Id, song => song);
if (savedSongs != null)
{
foreach (var publishedSong in savedSongs)
{
var key = publishedSong.Id;
if (lookupDetails.ContainsKey(key))
{
var details = lookupDetails[key];
publishedSong.SongName = details.SongName;
}
db.SongCategories.Add(new SongCategoryViewModel { PublishedSongId = key, CategoryId = //categories id that user typed in on editorFor});
db.PublishedSongs.Add(publishedSong);
db.SaveChanges();
}
}
}
return View("Index");
}
I'v filled CategoryViewModel table up with data in my SQL.
1) How do I get the titles of CategoryViewModel and pass them in the SelectList(//Here) parameter in my viewmodel?
2) In the PublishMusic Action, how do I get the CategoryId for the SongCategoryViewModel from the one or more categories that the user selected from songDetails.Category?
I am not sure if I am on the right track with this. basically the categories are like tags, the user can select more than one. I'v also cut out unessential code to make easier to read.

Unsure how to insert item into database using Entity Framework with many to many relationship

I am trying to insert a product into my database with an associated category. One product can belong to several categories and obviously one category can have several products. When I insert, I am sure I am missing something in my controller method but I'm not sure what it is. I have a bridge table called ProductCategory that just has a ProductID and a CategoryID in it. That table is not getting populated when I do the insert.
Here is my controller method that is doing the insert:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditProduct([Bind(Include = "ID,itemNumber,product,description,active,PDFName,imageName,SelectedCategories")] ProductModel model)
{
if (ModelState.IsValid)
{
using (var context = new ProductContext())
{
context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
if (model.ID == 0)
{
// Since it didn't have a ProductID, we assume this
// is a new Product
if (model.description == null || model.description.Trim() == "")
{
model.description = "Our Famous " + model.product;
}
if (model.imageName == null || model.imageName.Trim() == "")
{
model.imageName = model.itemNumber + ".jpg";
}
if (model.PDFName == null || model.PDFName.Trim() == "")
{
model.PDFName = model.itemNumber + ".pdf";
}
Session["dropdownID"] = model.ID;
// I think I probably need some additional code here...
context.Products.Add(model);
}
else
{
// Since EF doesn't know about this product (it was instantiated by
// the ModelBinder and not EF itself, we need to tell EF that the
// object exists and that it is a modified copy of an existing row
context.Entry(model).State = EntityState.Modified;
}
context.SaveChanges();
return RedirectToAction("ControlPanel");
}
}
return View(model);
}
And my Product model:
public class ProductModel
{
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Index("ItemNumber", 1, IsUnique = true)]
[Display(Name = "Item #")]
public int itemNumber { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Product")]
[MaxLength(50)]
public String product { get; set; }
[Display(Name = "Description")]
[MaxLength(500)]
public String description { get; set; }
[DefaultValue(true)]
[Display(Name = "Active?")]
public bool active { get; set; }
[Display(Name = "Image Name")]
public String imageName { get; set; }
[Display(Name = "PDF Name")]
public String PDFName { get; set; }
[Display(Name = "Category(s)")]
public virtual ICollection<CategoryModel> ProductCategories { get; set; }
public int[] SelectedCategories { get; set; }
public IEnumerable<SelectListItem> CategorySelectList { get; set; }
//public ICollection<CategoryModel> CategoryList { get; set; }
public virtual BrochureModel Brochure { get; set; }
public IEnumerable<SelectListItem> BrochureList { get; set; }
[Display(Name = "Category(s)")]
public String CategoryList { get; set; }
public static IEnumerable<SelectListItem> getCategories(int id = 0)
{
using (var db = new ProductContext())
{
List<SelectListItem> list = new List<SelectListItem>();
var categories = db.Categories.ToList();
foreach (var cat in categories)
{
SelectListItem sli = new SelectListItem { Value = cat.ID.ToString(), Text = cat.categoryName };
//if (id > 0 && cat.ID == id)
//{
// sli.Selected = true;
//}
list.Add(sli);
}
return list;
}
}
public ProductModel()
{
active = true;
}
}
And my Category model:
public class CategoryModel
{
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Category Name")]
[MaxLength(50)]
public String categoryName { get; set; }
[MaxLength(50)]
public String categoryDBName { get; set; }
[DefaultValue(true)]
[Display(Name = "Active?")]
public bool isActive { get; set; }
//public virtual ICollection<ProductCategory> ProductCategories { get; set; }
public virtual ICollection<ProductModel> Products { get; set; }
}
Here is my Product context:
public class ProductContext : DbContext
{
public ProductContext()
: base("DefaultConnection")
{
Database.SetInitializer<ProductContext>(new CreateDatabaseIfNotExists<ProductContext>());
}
public DbSet<CategoryModel> Categories { get; set; }
public DbSet<ProductModel> Products { get; set; }
public DbSet<BrochureModel> Brochures { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Entity<CategoryModel>().ToTable("Categories");
modelBuilder.Entity<ProductModel>().ToTable("Products");
modelBuilder.Entity<BrochureModel>().ToTable("Brochures");
modelBuilder.Entity<ProductModel>()
.HasMany(p => p.ProductCategories)
.WithMany(p => p.Products)
.Map(m =>
{
m.ToTable("ProductCategory");
m.MapLeftKey("ProductID");
m.MapRightKey("CategoryID");
});
//modelBuilder.Entity<CategoryModel>()
//.HasMany(c => c.ProductCategories)
//.WithRequired()
//.HasForeignKey(c => c.CategoryID);
}
public System.Data.Entity.DbSet<newBestPlay.Models.RegisterViewModel> RegisterViewModels { get; set; }
}
Let me know if other code or more info is needed.
You're never doing anything with your SelectedCategories array. You need to use this to pull CategoryModel instance from the database and then associate those with the product.
context.Categories.Where(c => model.SelectedCategories.Contains(c.ID)).ToList()
.ForEach(c => model.ProductCategories.Add(c));
...
context.SaveChanges();
UPDATE
Can I ask how to list out the categories for each product in my view?
That's kind of a loaded question, as it's highly dependent on what type of experience you're trying to achieve. Generally speaking, with any collection, you'll need to iterate over the items in that collection and then render some bit of HTML for each item. You can do this in a number of different ways, which is why there's not really one "right" answer I can give you. However, just to give you an idea and not leave you with no code at all, here's a very basic way to just list out the name of every category:
#string.Join(", ", Model.ProductCategories.Select(c => c.categoryName))

2 models with one to many relationship - How to list the count of items in the first model

I had a tough time coming up with a good title. I am working on an MVC application using asp.net and Entity Framework. I have 2 models, Categories and Products. There can be many products in each category. I have a page that lists out each category and each product with the associated fields for each. I want to add a column(field) to the Category list that lists how many products are in that category. I have no idea how to go about doing this. I am guessing I will need to add an additional variable to the Categories model called "productCount" or something like that.
Category model:
public class CategoryModel
{
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Category Name")]
[MaxLength(50)]
public String categoryName { get; set; }
[DefaultValue(true)]
[Display(Name = "Active?")]
public bool isActive { get; set; }
}
Product model:
public class ProductModel
{
public int ID { get; set; }
[Required(ErrorMessage = "Required")]
[Index("ItemNumber", 1, IsUnique = true)]
[Display(Name = "Item #")]
public int itemNumber { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Product")]
[MaxLength(50)]
public String product { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Description")]
[MaxLength(500)]
public String description { get; set; }
[DefaultValue(true)]
[Display(Name = "Active?")]
public bool active { get; set; }
[Display(Name = "Image Name")]
public String imageName { get; set; }
[Display(Name = "PDF Name")]
public String PDFName { get; set; }
[ForeignKey("Category")]
public int CategoryID { get; set; }
public virtual CategoryModel Category { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
public static IEnumerable<SelectListItem> getCategories()
{
using (var db = new ProductContext())
{
List<SelectListItem> list = new List<SelectListItem>();
var x = db.Categories.ToList();
foreach (var y in x)
{
list.Add(new SelectListItem { Value = y.ID.ToString(), Text = y.categoryName });
}
return list;
}
}
}
Admin Model:
public class AdminModel
{
public IEnumerable<CategoryModel> Categories { get; set; }
public IEnumerable<ProductModel> Products { get; set; }
public RegisterViewModel RegisterUsers { get; set; }
}
And here is the Controller method that lists the categories:
public ActionResult ControlPanel()
{
ViewBag.Message = TempData["Message"] == null ? "" : TempData["Message"].ToString();
//using (var db = new )
using (var db = new ProductContext())
{
var categories = from c in db.Categories
select c;
categories = categories.OrderByDescending(c => c.isActive);
var model = new AdminModel
{
Categories = categories.ToList(),
Products = db.Products.ToList()
};
return View(model);
}
}
For a single categoryID you can just use Linq's Count():
int specificCategoryID = 15;
return db.Products.Where(w => w.CategoryID == specificCategoryID).Count();
For a list of key/value pairs of categoryIDs and the count of products, something like this:
var products = db.Products.AsEnumerable();
var productCount = products.GroupBy(p => p.CategoryID,
(k, v) => new { CategoryID = k, ProductCount = v.Count() });
I would recommend using a proper viewmodel and making sure that it only uses one query so you dont run into a select n+1 issue.
Edit:
Assuming you always have a list of all categories and products you can just do the calculation in the Admin ViewModel on the items you already pulled from the DB:
public class AdminModel
{
public IEnumerable<CategoryModel> Categories { get; set; }
public IEnumerable<ProductModel> Products { get; set; }
public RegisterViewModel RegisterUsers { get; set; }
public int GetProductCountForCategoryID(int categoryID)
{
return this.Products
.Count(w => w.CategoryID == categoryID);
}
}
Then in the view, just pass in whatever category ID like this:
#Model.GetProductCountForCategoryID(categoryID);

Model value not accessable

I have a model which holds some details about an account (Name, Id etc) and then it has a type called Transaction, which holds information about the currently selected account transaction. A transaction can then have many transaction lines. So I have a List<TransactionsLine> property.
I am trying to set the value of a Drop down list, using the model, the value being in the List<> property. At the moment, there can, and must, only be one item in the list.
#Html.DropDownListFor(x=>x.Transaction.TransactionLines[0].CategoryId, Model.TransactionReferences.Categories, new {#onchange="populateSubCategory()"})
However, when I run this, the list defaults to the first item in the list.
In debug mode, when I hover the mouse over x.Transaction.TransactionLines[0].CategoryId, it doesn't show me a value. But when hover over the collection, Model.TransactionReferences.Categories, I see it has a valid list. It just won't set the selected value.
Am I doing this wrong?
It works in other drop downs I use, BUT the select value is in the top most level of my model:
#Html.DropDownListFor(x => x.Transaction.ThirdPartyId, Model.TransactionReferences.ThirdParties, new { #class = "cmbThirdParty form-control", #onchange = "populateDefaults()" })
That one works fine.
Note, doing it manually, works:
<select class="form-control" id="cmbCategory" onchange="populateSubCategory()">
<option value="0">Select a One</option>
#foreach (var cat in Model.TransactionReferences.Categories)
{
//var selected = cat.Value == Model.Transaction.TransactionLines[0].CategoryId.ToString() ? "selected" : "";
<option value="#cat.Value">#cat.Text</option>
}
</select>
But doesn't feel like the best way to do it.
Model:
The main model passed to the view:
public class TransactionModel
{
public int BankAccountId { get; set; }
public string BankAccountName { get; set; }
public TransactionContainer Transaction { get; set; }
public TransactionReferenceModel TransactionReferences { get; set; }
public DateTime DefaultDate { get; set; }
}
The TransactionReferenceModel holds all my 'reference' data used to populate drop down lists:
public class TransactionReferenceModel
{
public List<SelectListItem> TransactionTypes { get; set; }
public List<SelectListItem> EntryTypes { get; set; }
public List<SelectListItem> SubCategories { get; set; }
public List<SelectListItem> Categories { get; set; }
public List<SelectListItem> ThirdParties { get; set; }
public List<SelectListItem> CostCentres { get; set; }
}
The TransactionContainer model holds allthe main details about the selected transaction:
public class TransactionContainer
{
public int Id { get; set; }
public int AccountId { get; set; }
public int TransactionTypeId { get; set; }
public string TransactionType { get; set; }
public int EntryTypeId { get; set; }
public string EntryType { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/dd/yyyy}")]
public DateTime TransactionDate { get; set; }
public string ThirdParty { get; set; }
public int ThirdPartyId { get; set; }
public string Account { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
public decimal Amount { get; set; }
public string Notes { get; set; }
public string CategoryDisplay { get; set; }
public string CostCentreDisplay { get; set; }
public decimal RunningBalance { get; set; }
public List<TransactionLine> TransactionLines { get; set; }
}
That then holds a list of transaction lines that make up the transaction. The transaction line holds the property I am trying to set the drop down to, which is CategoryId:
public class TransactionLine
{
public int Id { get; set; }
public int TransactionId { get; set; }
public int? CostCentreId { get; set; }
public string CostCentre { get; set; }
public int SubCategoryId { get; set; }
public string SubCategory { get; set; }
public int CategoryId { get; set; }
public string Category { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
public decimal Amount { get; set; }
public string Notes { get; set; }
}
And here is how I am populating my model and sending it to the view:
public ActionResult EditTransaction(int? transactionId, int? bankAccountId)
{
// Create the main view object
var model = new TransactionModel
{
Transaction = new TransactionContainer
{
TransactionLines = new List<TransactionLine>()
}
};
if (transactionId != null) // This is an Edit, as opposed to an Add
{
var item = new TransactionService(currentUserId).GetTransaction(transactionId.Value);
// Populate the Reference object used to populate drop downs.
model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, item.TransactionLines[0].SubCategoryId);
model.BankAccountId = item.AccountId;
model.BankAccountName = item.Account.FullName;
model.DefaultDate = Session["DefaultDate"] != null
? DateTime.Parse(Session["DefaultDate"].ToString())
: DateTime.UtcNow;
model.Transaction.AccountId = item.AccountId;
model.Transaction.Amount = item.Amount;
model.Transaction.TransactionLines.Add(new TransactionLine
{
Id = item.TransactionLines[0].Id,
CategoryId = item.TransactionLines[0].SubCategory.CategoryId,
CostCentreId = item.TransactionLines[0].CostCentreId,
Notes = item.TransactionLines[0].Notes,
Amount = item.TransactionLines[0].Amount,
SubCategoryId = item.TransactionLines[0].SubCategoryId,
TransactionId = model.Transaction.Id
});
model.Transaction.EntryTypeId = item.EntryTypeId;
model.Transaction.Id = transactionId.Value;
model.Transaction.Notes = item.Notes;
model.Transaction.ThirdPartyId = item.ThirdPartyId;
model.Transaction.TransactionDate = item.TransactionDate;
model.Transaction.TransactionTypeId = item.TransactionTypeId;
}
else
{
// Populate the bank account details
var bank = new BankAccountService(currentUserId).GetBankAccountById(bankAccountId.Value);
model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, null);
model.BankAccountId = bank.Id;
model.BankAccountName = bank.FullName;
model.Transaction.TransactionLines.Add(new TransactionLine
{
TransactionId = model.Transaction.Id // Link the transaction line to the transaction.
});
var transactionDate = Session["DefaultDate"] != null
? DateTime.Parse(Session["DefaultDate"].ToString())
: DateTime.UtcNow;
// Populate the object to hold the Transaction data, so that we can use it and return it in the view.
model.Transaction.TransactionDate = transactionDate;
}
return View(model);
}
I think you should use the SelectList Constructor in your view, in order to indicate the default value, like this:
#Html.DropDownListFor(
x => x.Transaction.TransactionsLines[0].CategoryId,
new SelectList(Model.TransactionReferences.Categories, "Value", "Text", Model.Transaction.TransactionsLines[0].CategoryId)
)
You are not restricted to use List< SelectListItem > for the collections. You can use a List of a specific class also.
This is the Controller Action Method code:
public class HomeController : Controller
{
public ActionResult Index()
{
var m = new AccountModel();
m.Transaction = new Transaction();
m.Transaction.TransactionsLines = new List<TransactionsLine>();
m.Transaction.TransactionsLines.Add(new TransactionsLine() { CategoryId = 2 });
m.TransactionReferences = new TransactionReferences();
m.TransactionReferences.Categories = new List<SelectListItem>()
{ new SelectListItem() { Text = "Cat1", Value = "1" },
new SelectListItem() { Text = "Cat2", Value = "2" },
new SelectListItem() { Text = "Cat3", Value = "3" }
};
return View(m);
}
}

Resources