简体   繁体   中英

Add prefix to control id and still have it bind MVC Razor

I have a case where I have a page displaying an order and tabs that display the order details. The order details are quite complex and since they are the same layout, I want to use a partial view or editor template that will generate the form.

The problem is the result is multiple duplicate form input id's are generated (one for each order detail. For example, I have:

foreach (var orderDetail in Model.OrderDetils)
{
    @Html.EditorFor(model => orderDetail, "WorkOrder", orderDetail)
}

I've read much about this and see solutions where it is recommended to use an editortemplate, but that solution only works when you have the same form to render, but passing it different model properties so the control id's prefixes will differ...ie. like this solution .

In my case, this won't work as the model property I am passing is always the same.

So how else can I create unique Id's in the partial or editor template that will also bind.

I know instead of:

@Html.EditorFor(model => model.WOHdr.Attribute1)

I could do:

@Html.TextBoxFor(model => model.WOHdr.Attribute1, new { id = Model.Id + "_Attribute1" })

But then it won't bind when it passes to the controller.

Thoughts?

Try this

@Html.TextBoxFor(model => model.WOHdr.Attribute1, new { @id = @Model.Id + "_Attribute1" })

Use "@"+dynamic value. Now You will get unique Id's

In EditorFor you can use like this

@Html.EditorFor(model => model.WOHdr.Attribute1, null, "id=" + @Model.Id + "" )

the id will generate like this

id="id_1", id="id_2" and so on..

<input id="Checkbox1_@(test.TestId)" type="checkbox" />

我希望上层代码可以帮到你

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