Do Knockout databinding for DropDownList through @Html.DropDownList.

2,994 views
Skip to first unread message

Myhailo Yavorskyi

unread,
Oct 22, 2012, 10:06:08 PM10/22/12
to knock...@googlegroups.com
Hey, guys.
 
I'm pretty new to both Knockout and ASP.NET MVC. So, please, bear with me. Right now I have the following in the view:
 

@Html.DropDownList(

"Distance", ViewData["Radius"] as SelectList )

It renders the following HTML:

<select id="Distance" name="Distance">
<option>5</option>
<option>10</option>
<option>15</option>
</select>
 
But, I need <select id="Distance" name="Distance"> to render as
<select id="Distance" name="Distance" data-bind="value: SearchRequest.Radius">
 
How do I add data-bind="optionsValue: studentSearchRequest.Radius" through @Html.DropDownList? I know there's an htmlAttributes parameter on @Html.DropDownList, but I don't know how to use it in this particular scenario.
 
Thanks a lot in advance,
Myhailo
 
 

Myhailo Yavorskyi

unread,
Oct 23, 2012, 2:30:20 AM10/23/12
to knock...@googlegroups.com

Ok, I think I had figured it out. My problem was that I was trying something like

 
@Html.DropDownList(
"Distance", ViewData["Radius"] as SelectList, new { data-bind = "optionsValue: SearchRequest.Radius" })
 
However, as weird as it seems to me what works is
 

@Html.DropDownList(

"Distance", ViewData["Radius"] as SelectList, new { data_bind = "optionsValue: studentSearchRequest.Radius" })

with the only difference being that I had to use "data_bind" insted of "data-bind" even though it's the "data-bind" that's the Knockout.js construct. I'm not sure if my overall approach will work, but at least the correct HTML , i.e

<select id="Distance" name="Distance" data-bind="value: SearchRequest.Radius">

is rendered in this case.


 

Alessandro Ghidini

unread,
Oct 23, 2012, 3:40:38 AM10/23/12
to knock...@googlegroups.com
The dash simbol can't be used because it would be interpreted like the minus operation. Starting from MVC3 they added an helper which replaces attributes underscores with dashes: http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.anonymousobjecttohtmlattributes(v=vs.98).aspx

Inviato da iPad

Myhailo Yavorskyi

unread,
Oct 23, 2012, 4:13:07 AM10/23/12
to knock...@googlegroups.com
That explains it. Thanks a lot.
Reply all
Reply to author
Forward
0 new messages