Fraz Sundal
Fraz Sundal

Reputation: 10448

Problem Creating dynamic Id for textbox in asp.net mvc

I have 3 textboxes in three different tab control and i want to generate textbox id like textbox plus concatenate the tab number

for(int i=0;i<3;i++)
{
    <%: Html.TextBoxFor(e=>e.vcr_LinkName + i)%>
}

its not working but when i change it to

 for(int i=0;i<3;i++)
    {
        <%: Html.TextBox("vcr_LinkName" + i)%>
    }

it works fine. but i want to use textboxfor instead of textbox

Upvotes: 1

Views: 2185

Answers (1)

Mattias Jakobsson
Mattias Jakobsson

Reputation: 8237

You can't really use textboxfor in this way as you don't have a property on your model that you want to bind it to. You do, however, have a few other options.

You could have a list of strings on your model and do something like this:

for(int i = 0; i < 3; i++)
{
    <%:Html.TextBoxFor(x => x.LinkNames[i])%>
}

You could build your own helper like this:

public static MvcHtmlString TextBoxWithSuffix<TModel, TProperty>(this HtmlHelper helper, Expression<Func<TModel, TProperty>> expression, string suffix)
{
    var id = ExpressionHelper.GetExpressionText(expression);
    return helper.TextBox(string.Format("{0}{1}", id, suffix);
}

And use it like this:

for(int i = 0; i < 3; i++)
{
    <%:Html.TextBoxWithSuffix(x => x.vcr_LinkName, i.ToString())%>
}

Upvotes: 1

Related Questions