views:

102

answers:

1

I'm using same partial view in create.aspx view page twice, part of my code is: <%Html.RenderPartial("LocationVerifyControl"); %> <%Html.RenderPartial("LocationVerifyControl"); %>

In the mvc view user controls, it had a button and test code for it: $('#btnVerify').click(function() { alert("clicked by btnVerify");}

I watched the warning dialog pop up twice when clicked the button, the main view page had contents with same ids. How to solve this kind of problems? To prevent same ids in main view page, put my using html ids in the view data and pass them to partial view?

+1  A: 

If I understand your question correctly, you are looking to add unique functionality to two different buttons with the same id.

It's not really valid to have more than one element with the same id. If there will be multiple you should just make it a class. You might want to first run your markup through W3C Validation.

Second you can do this by wrapping the partials in a div or whatever element you like. Something like this:

<div id="first">
    <% Html.RenderPartial("LocationVerifyControl"); %>
</div>

<div id="second">
    <% Html.RenderPartial("LocationVerifyControl"); %>
</div>

Then your script section can reference the buttons independently.

$('#first #btnVerify').click(function () {
    alert('first button click');
});

$('#second #btnVerify').click(function () {
    alert('second button click');
});

Notice that I'm just saying to find the id=first then find a id=btnVerify within the id=first.

Steve Hook
Yes, if put those script code in main page, it can work. But I want to rewrite a asp.net web user control to a mvc view user control, to encapsulate the partial view ("LocationVerifyControl") which has its own script code, how can it know the outside div id("first" or "second") in partial view?
Leo Wang
@Leo Wang I see. You could do like you hinted at. Pass in a new Guid in your ViewModel for the partial. Drop the guid in the id of a div or some container element. Then also use the guid reference in the script section (in the partial). It would look something like this: $('<%: Model.Guid %> #btnVerify')
Steve Hook
Yeah, I have solved this problem by binding a viewmodel for the partial view, this viewmodel class stored a id, render partial view like this:<%Html.RenderPartial("LocationVerifyControl", new LocationCtrlId("first")); %>then, in partial view code, add a div include all html code:<div id="<%=Model.Id().ToString()%>"> blah......</div>and jquery code like this:$("#<%=Model.Id().ToString()%> #btnVerify").click()This may be a good way for encapsulating partial view as a independent user control.
Leo Wang