I am newbie in MVC Razor and I want to implement validation message on textboxes. Here I'm creating some textbox dynamically as follows:
View Code:
foreach (var items in (IEnumerable<System.Data.DataRow>)Model.UsersOfList)
{
@Html.TextBoxFor(m => m.LoginNameOfLoginInfoTab, new { @class = "textBox_LoginInfoAndPermission", @value = (Model.LoginNameOfLoginInfoTab = items["UserName"].ToString()), @id = ("txtUserLoginName" + Model.UsernameOfLoginInfoTab.Trim()) })
@Html.ValidationMessageFor(m => m.LoginNameOfLoginInfoTab, null, new { @class = "ErrorMessage" })
@Html.TextBoxFor(m => m.UsernameOfLoginInfoTab, new { @class = "textBox_LoginInfoAndPermission", @value = (Model.UsernameOfLoginInfoTab = items["FirstName"].ToString()), @id = ("txtUserName" + Model.UsernameOfLoginInfoTab.Trim()) })
@Html.ValidationMessageFor(m => m.UsernameOfLoginInfoTab, null, new { @class = "ErrorMessage" })
}
in the module I've written code for validation as follows:
[Required (ErrorMessage="*")]
public string UsernameOfLoginInfoTab
{
get;
set;
}
[Required(ErrorMessage = "*")]
public string LoginNameOfLoginInfoTab
{
get;
set;
}
Now when all textboxes has been created and when one validation message is displaying for first loop iteration textbox then it will automatically displaying in front of another textbox too which is created on second loop iteration.
Please tell me whats going wrong.
The problem is because the expression you're using in
TextBoxFor
andValidationMessageFor
, which is used by MVC to create a string name for the field and look up validation messages fromModelState
, is always the same throughout the iteration of the loop.Your approach here seems a bit flawed, so my answer is more comprehensive.
1) Make view models that structurally represent the info you are trying to display.
Fix your view models:
Fix your action (I'm making this up here to illustrate a point):
2) Now you can iterate through users in your view and create proper fields with validation messages.
Let's call this view
ListOfUsers.cshtml
. Include whatever other things you need in your view, but use afor
loop instead.This will result in HTML like this for each item (
0
in the name and id will be the index of the user in the collection):3) Create an action to receive submitted changes. This action will automatically bind the submitted values to the
model
argument, and do validation for you. All you need to do is checkModelState.IsValid
.