简体   繁体   中英

Adding DisplayName attribute dynamically in asp.net mvc4

I have an asp.net mvc4 razor form that contains a series of checkboxes. The checkboxes are populated from a list that is generated dynamically. The list is in the below model:

public class UserViewModel
{
    [Required]
    [MaxLength(32)]
    [DataType(DataType.Text)]
    [DisplayName("ID")]
    public string UserId { get; set; }

    public List<SkillSetSelector> SkillSets { get; set; }
}

public class SkillSetSelector
{
    public string Code { get; set; }

    public string Description { get; set; }

    public bool Selected { get; set; }
}

I am then populating the checkboxes in the form thus:

    @for (int i = 0; i < Model.SkillSets.Count;i++ )
{
    <div>
 <table class = "searchtable">
 <tr>
 <td>
 @Html.CheckBoxFor(m => m.SkillSets[i]) @Model.SkillSets[i].Description</td>
</tr>
</table>
</div>
    }

My problem is that I would like to assign the DisplayName attribute of each checkbox dynamically. Ie I want it to be the same value as Skillsets[i].Description. Currently when the model is sent back to the controller there is no was of knowing which item it each check box belongs to as the description is returned null - the selected value is correct but you have nothing except the order of the fields to tell you which item is which. Is there any way of doing this? The checkboxes have to be dynamic as the data they are based on is user definable. Thanks.

DisplayName data annotation attributes require constant values. You cant set it dynamically.

But you can refer the values from Resource files or create your own Custom Model Meta Data Provider for this Please check this Article forCustom Model MetaData Provider implementation

Thanks for your help Murali.

In the end I got around the problem of not knowing which item was what when it was sent back by adding a hidden textbox with the item's id:

@for (int i = 0; i < Model.SkillSets.Count;i++ )
{
    <div>
 <table class = "searchtable">
<tr>
<td>
<div>
@Html.CheckBoxFor(m => m.SkillSets[i].Selected) @Model.SkillSets[i].Description
</div>
</td>
<td>
<div>
@Html.TextBoxFor(m => m.SkillSets[i].ID, new {id = "custselecthidden" })
</div>
</td>
</tr>
</table>
</div>
}

That way the ID was sent back in the model and I now know what is what.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM