Dhanilan
Dhanilan

Reputation: 183

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>

Upvotes: 7

Views: 7066

Answers (4)

Squall
Squall

Reputation: 830

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.

Upvotes: 9

Jaimin
Jaimin

Reputation: 8020

This is just an example it add TestBox on button click based on user need all text box with diffrent id . You should do something like this in your PartialView Code

Script

<script type="text/javascript">
    $(document).ready(function () {
        var count = 0;
        $("#AddControls").click(function () {
            count++;
            var elements = "<input type='text' id='txt" + count + "'class='required'/><br/></br>";
            $("#dynamicControldiv").append(elements);
            // $(".required").rules("add" + count, "required");
        });

        $("#btnDynamicSubmit").on("click", function () {
            var textlength = $("input[type='text']").attr("class", "required");
            for (var i = 1; i <= textlength.length; i++) {
                var id = $("#txt" + i).attr('id');
                var value = $("#txt" + i).attr('value');
                if (value == "") {
                    $("#txt" + i).attr("required", "required");
                }
            }
            var validation = $("#dynamicControlForm"); //Your form id.
            if (!validation.valid()) {
                $("input[type='text']").attr("required", "required");
                return false;
            }

        });
    });
</script>

View

 <input type="button" name="CreateControl" value="AddControl" id="AddControls" />
    <form action="/" method="post" id="dynamicControlForm">
    <div id="dynamicControldiv">
    </div>
    <input type="submit" name="DynamicControl" id="btnDynamicSubmit" value="Submit" />
    </form>

Upvotes: 1

PeaceFrog
PeaceFrog

Reputation: 717

In cases like this, where you have N number of the same thing on the page, I think it's best stop replying on the id's and instead use relative logic.

In your case that would mean handling the click event of the submit button and applying your post logic to the form it is in.

You can use a jQuery selector that is not dependent on ID to do the binding. See the code below that uses a class selector.

Sample HTML

<form name="myForm">
    <input class="buttonFromPartial" name="myButton" type="button"  />
</form>
<form name="myForm">
    <input class="buttonFromPartial" name="myButton" type="button"  />
</form>

Click handler

$("input.buttonFromPartial").click(function () {
    var $form = $(this).closest("form");
    //do your post logic here
}

Upvotes: 2

Aviran Cohen
Aviran Cohen

Reputation: 5691

Create a helper or javascript code that generates a random id, in either server or client side.

C# Function in the server side inside the view example:

@function string GenerateId(string prefix)
{
return string.Format("{0}_{1}",prefix,Guid.NewGuid().ToString("N"));
}

Javascript function in the client side inside the view example:

function generateId(string prefix) {
  return prefix + Math.floor((1 + Math.random()) * 0x10000)
             .toString(16)
             .substring(1);
};

Create inside the partial view a variable that contains the generated value and use it.

@var buttonId = GenerateId("button")
// buttonId = "button_85021948560128"
...

This way every partial view will generate its own unique ids.

Upvotes: 3

Related Questions