Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminating Duplicate Id in partial view MVC 3 razor

I have a page which adds dynamic partial views based on user interaction.Also the same partial view can be added as many times.Each partial view performs submit through JQuery and AJAX.What is the best way to avoid duplicates for Ids across the page.It is very important because JQuery functions uses the ID selector.Please provide me a solution.

Partial View1

<script type="text/javascript"> 
    $(function () {
        $("#MyButton1")
            .button()
            .click(function () {
                alert("MyButton1 clicked From MyForm1 ");
            });
    });
</script>
<div><p>MyForm1</p></div>
<form id="MyForm1" >
    <input id="MyButton1" type="button" value="buttonFromPartial1" />
 </form>

Partial View2

<script type="text/javascript"> 
    $(function () {
        $("#MyButton1")
            .button()
            .click(function () {
                alert("MyButton1 clicked From MyForm2 ");
            });
    });
</script>
<div><p>MyForm2</p></div>

<form id="MyForm2" >
    <input id="MyButton1" type="button" value="buttonFromPartial2" />
</form>
like image 606
Dhanilan Avatar asked Sep 07 '13 10:09

Dhanilan


Video Answer


1 Answers

Not sure if it's still useful to you, but in Razor I use TemplateInfo to prefix my partial view IDs when I find the engine is creating duplicate IDs.

Usage:

@Html.Partial("MyPartialView", new MyModel(), new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "PrefixGoesHere" } })

This will produce an ID similar to this: YourPrefix_MyModelProperty.

Avoids a whole lot of unnecessary helper methods and javascript.

like image 118
Squall Avatar answered Sep 28 '22 09:09

Squall