2

Could some please convert the following code to a standard html tag? Something like <select id="selectDomain" name="selectDomain">, IF it converts to a select tag.

@Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>(), "", new { id = "selectDomain", name = "selectDomain"})

If I understand correctly, doesn't x => x.domain mean id="domain" name="domain"? Is this code overwriting the name and id to selectDomain?

Finally, if it isn't convertible to an html tag, I want to add a class to the given code. I tried adding it inside the new{} like new{id="selectDomain", name="selectDomain", class="form-control"} section but it gave me error saying expected }

4
  • 2
    If you want to add a class attribute, you will need to use the '@' before 'class' because class is a reserved word: new{id="selectDomain", name="selectDomain", @class="form-control"} Commented Mar 30, 2016 at 15:00
  • 3
    Why don't you run application and view source in browser? Commented Mar 30, 2016 at 15:01
  • @ElConrado haha am i really that dumb? doesn't really make much sense with all the attributes but I got it, thanks :P Commented Mar 30, 2016 at 15:05
  • @Nava-Prev.Queti yes, that did the trick! Thanks Commented Mar 30, 2016 at 15:05

2 Answers 2

2

You understand correctly if you write:

@Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>())

Razor will produce:

<select id="domain" name="domain"> </select>

It's better to use ViewModel and create property selectDomain in it and then:

@Html.DropDownListFor(x => x.selectDomain, Enumerable.Empty<SelectListItem>(), new { @class="form-control" })

Will make html that you want.

But if you don't want to do it you can use Html.DropDownList helper like this:

@Html.DropDownList("selectDomain",Enumerable.Empty<SelectListItem>(), new { @class="form-control" })

note escaped class with @ symbol.

Sign up to request clarification or add additional context in comments.

4 Comments

I like the approach using viewmodel it makes the code more readable
@FedriQrueger yeap, that's clean MVC way
I have a ViewModel with domain as the property
@BivoKasaju Razor helpers uses your property name as name and id tag attributes value. So you should change property name if you want different output. Or just use DropDownList helper where you can pass name as param.
1

You can specify "name" with uppercase first letter (works in MVC5)

 @Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>(), "", new { id = "selectDomain", Name = "selectDomain"})

result:

  <select name="selectDomain" id="selectDomain">

1 Comment

Never do this! It will ensure that model binding fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.