Friday, 15 July 2011

asp.net mvc 4 - Razor, TextBoxFor for ICollection property -



asp.net mvc 4 - Razor, TextBoxFor for ICollection property -

//product

public class product { [key] public int id {get; set;} public string pk {get; set;} [required(errormessage="category required field.")] public int categoryid { get; set; } [required] public string title {get; set;} public virtual icollection<pricing> pricing { get; set; } }

// pricing

public class pricing { [key] public int id {get; set;} public int productid {get; set;} public decimal cost {get; set;} public int orderqty {get; set;} public string pk { get; set; } }

i have above entities table, , want draw 5 textbox icollection in update product page. have no idea, how should do.

@model browniedal.entities.product <th> cost / order qty</th> <td> @{int pricecnt = 0;} @foreach(var cost in model.pricing){ pricecnt++; @html.textboxfor(model => price.price) @html.textboxfor(model => price.orderqty) <br /> } @if (pricecnt < 5) { // ??? @html.textboxfor(model.pricing => model.pricing.price) pricecnt++; } </td>

when tried '@html.textboxfor(model.pricing => model.pricing.price)', got error say:

error 1 'system.collections.generic.icollection<pj.entities.pricing>' not contain definition 'price' , no extension method 'price' accepting first argument of type 'system.collections.generic.icollection<pj.entities.pricing>' found (are missing using directive or assembly reference?)

anybody know, how should drawing textbox icollection<> property?

i'd recommend using editor templates.

so initialize pricing collection in controller , finish 5 elements:

model.pricing = ... go pricing collection wherever getting int count = model.pricing.count(); if (count < 5) { // have less 5 elements in collection => let's finish // empty pricing elements: var emptyitems = enumerable.range(1, 5 - count).select(x => new pricing()); model.pricing = model.pricing.concat(emptyitems).tolist(); } homecoming view(model);

and within view simply:

@model browniedal.entities.product <table> <thead> <tr> <th>price / order qty</th> </tr> </thead> <tbody> @html.editorfor(model => model.pricing) </tbody> </table>

and define custom editor template pricing model (~/views/shared/editortemplates/pricing.cshtml):

@model browniedal.entities.pricing <tr> <td> @html.textboxfor(model => model.price) @html.textboxfor(model => model.orderqty) </td> </tr>

simply simple. no need worry loops, no need worry indexes, asp.net mvc framework take care everything. need follow conventions built in.

razor asp.net-mvc-4

No comments:

Post a Comment