javascript - Client Side Validations not working for second row in ASP.NET MVC -
model below:
public class user { [displayname("id")] [range(0, 9999)] public int id { get; set; } public string mask { get; set; } }
and controller returns iqueryable of above model
there 2 views. parent view , partial view renders each row model
main view
@model iqueryable<user> @{ var array = model.toarray(); } //header here <tbody id="table-body-vlan"> @{ (var = 0; < array.length; i++) { html.renderpartial("_addrow", array [i], new viewdatadictionary() { { "index", } }); } } </tbody> </table> </div> }
**and partial view **
@model user @{ var index = viewdata["index "]; } <tr class="js-deletable-item" id="row-@index" data-id="@model.id" > <td class="editable"> @html.textboxfor(v => model.id, new {name = "id[" + index + "]", id = "id-" + model.id, value = model. id > 0 ? model. id.tostring() : ""}) </td> <td class="editable"> @html.textboxfor(v => model.name, new {name = "id[" + index + "].name", data_val = "false" }) </td> </tr>
issue below: if there 10 records in iqueryable client side validations applies first row.
e.g. if type 101s id field in first row gets warning (by changing background color) invalid id. if same second or other rows don't see background color change. client side validations (defined through data annotations) applying first row.
i guess after first row rendered not adding annotation related properties other rows.
i suggest take @ editor , display templates in mvc:
create editor template here : ~/views/shared/editortemplates/user.cshtml
this:
@model user <tr class="js-deletable-item"> <td class="editable"> @html.textboxfor(m => m.id) </td> <td class="editable"> @html.textboxfor(m => m.name) </td> </tr>
this automatically rendered each element of model whenever call editorformodel
.
in controller, .tolist()
on iqueryable<user>()
object, before sending view.
in main view:
@model ienumerable<user> <table> <thead> <tr> <td>id</td> <td>name</td> </tr> </thead> <tbody> @html.editorformodel() </tbody> </table>
much simpler , cleaner right? main advantage of using these templates is, automatically create appropriate name
attributes. like:
<input data-val="true" name="[0].id" value="" /> <span class="text-danger field-validation-valid" data-valmsg-for="[0].id"></span>
each row gets unique name
attribute. in code, rows have same name="id"
, data-valmsg-for="id"
. because of this, first row getting validated.
the name
attributes crucial when forms containing collections
being submitted. otherwise, user list end being null
when submit (refer).
if don't want use editortemplates
, you'd have for
loop (not foreach
) , populate rows.
Comments
Post a Comment