Mike
Mike

Reputation: 409

html helper - how do I get rid of the name attribute?

I have a strongly typed partial view. The model has a property that is a list of users in Active Directory represented by a class called ADUser.

I have a partial view that represents a drop down list for this property. While I use the value of this drop list for some other things, I have no need to submit its value, so I thought I would remove the name attribute. However, once the Html loads, the name attribute is always set to what the Html helper wants to assign it. Is there a way I can remove that attribute so that the drop down's value doesn't submit?

In my main partial view (_adusers is the name of the list):

<%: Html.Partial("ADUserDropDown", Model._adusers)%>

In my drop down's partial view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<MyProject.Models.ADUser>>" %>

<%= Html.DropDownList("", new SelectList(Model, "ValueText", "DisplayText"), new { name = "", size = "12" })%>
<input type=button value="Search..." />
<input type=button value="Close" />

This results in:

<select name="_master" size="12">

_master being the name of the parent model. If I add something to the first parameter of Html.DropDownList, it results in:

<select name="_master.WhateverINamedIt" size="12">

I want to achieve:

<select size="12">

Upvotes: 0

Views: 463

Answers (1)

Zabavsky
Zabavsky

Reputation: 13640

There is no point of using the HTML helper then. You can change the code of the partial view to:

<select size="12">
@foreach(var item in Model)
{
    <option value="@item.ValueText">@Html.DisplayFor(m => item.DisplayText)</option>
}
</select>

However if you want to stick with the DropDownList helper the name parameter in the html attributes has to be specified with the capital letter:

<%= Html.DropDownList("", new SelectList(Model, "ValueText", "DisplayText"),
    new { Name = string.Empty, size = "12" })%>

As an alternative you can remove the name with jQuery:

$('[name="_master.WhateverINamedIt"]').removeAttr('name');

Don't like or use jQuery, the plain javascript will do the job:

document.getElementsByName('_master.WhateverINamedIt')[0].removeAttribute('name');

Upvotes: 1

Related Questions