开发者

Does ASP.NET MVC have a way to generate unique ClientIDs?

开发者 https://www.devze.com 2022-12-21 16:09 出处:网络
Is there an out-of-the-box way to create unique \"id\" tags in ASP.NET MVC? (Similar to the dreaded but sometimes useful ClientIDs in WebForms?)

Is there an out-of-the-box way to create unique "id" tags in ASP.NET MVC?

(Similar to the dreaded but sometimes useful ClientIDs in WebForms?)

This would be useful when rendering a partial view many times on a page.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%-- Example Partial View --%>
<div id="<%=GenerateAUniqueIDHere()%>">
Content
</div>
<script type="text/javascript">
    $("#<%=GenerateAUniqueIDHere%>").hide().fadein().css("font-size", "500%");
</scri开发者_开发知识库pt>

If not, it is easy enough to roll my own.

Thanks much,

Jon


Use a GUID?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
<%-- Example Partial View --%> 
<%
    string ID = Guid.NewGuid().ToString();
%>
<div id="<%=ID%>"> 
    Content 
</div> 
<script type="text/javascript"> 
    $("#<%=ID%>").hide().fadein().css("font-size", "500%"); 
</script>

I would also pass the GUID in as a viewdata object during the renderpartial method call to keep your ViewUserControl tidy


As far as I know, MVC does not have this. I have used ASP.NET MVC for over a year, and never had to use this. When I have several controls, with the same name, I almost always want to be able to query these controls later, so I need to know the Id, and use a counter, so I know the names. If you don't need to know their ids, why even give them a id?


From MSDN:

The chance that the value of the new Guid will be all zeros or equal to any other Guid is very low.

So there seems to be no way to make sure that an ID is absolutely unique. Using Guid seems to be a better solution than generating a random number on your own.

You could try generating the ID from the data or its description.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号