Let’s say I have a model class,
public class NameModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List<SelectListItem> Titles
{
get
{
var list = new List<SelectListItem>();
list.Add(new SelectListItem() { Text = "Mr.", Value = "Mr." });
list.Add(new SelectListItem() { Text = "Mrs.", Value = "Mrs." });
list.Add(new SelectListItem() { Text = "Ms.", Value = "Ms." });
return list;
}
}
public NameModel()
{
}
public NameModel(string first, string last)
{
this.FirstName = first;
this.LastName = last;
}
}
This class is used in view named ShowName.cshtml as follows
@model MyTestApp.Models.NameModel
@Html.DropDownListFor(m => m.Title, Model.Titles, Model.Titles)
<br />
@Html.LabelFor( m => m.LastName)
@Html.TextBoxFor( m => m.LastName)
<br />
@Html.LabelFor( m => m.FirstName)
@Html.TextBoxFor( m => m.FirstName)
I am using this class as a template ( meaning referred via EditFor ), So in one case when this class is used for Employee, in HTML the text box for LastName will have an id of Employee_LastName whereas if i used it for Manager, HTML id for this text box will be Manager_LastName. Problem is that if I have certain java-script/JQuery that uses these identifier, how can I refer to these text boxes because their Ids changed based upon where they are used?
Try creating your textbox as below
Or you can add css class and refer your controls using the class selector