I try to bind a dropdownlist in knockout with MVC 4. Here is my code:
Action
public JsonResult GetUserTypes()
{
using (QuestApplicationEntities db = new QuestApplicationEntities())
{
var usertypes = (from usertype in db.UserTypes
select new
{
usertype.Id,
usertype.Name
}).ToArray();
return Json(usertypes, JsonRequestBehavior.AllowGet);
}
}
Knockout.js
var Register =
{
Name: ko.observable("Ragesh"),
Email: ko.observable().extend({ email: true }),
Password: ko.observable(),
UserTypes: ko.observableArray([]),
UserType: ko.observable(),
SaveRegistration: function () {
//alert('saved');
$.ajax({
url: '/Home/RegisterUser',
type: 'post',
datatype: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function () {
alert('saved');
}
});
}
};
$.ajax({
url: '/Home/GetUserTypes',
type: 'post',
datatype: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function () {
ko.mapping.fromJS(data,Register.UserTypes);
}
});
ko.applyBindings(Register);
Html
<h4>Register</h4>
<fieldset>
<legend>New User Registration</legend>
<div class="editor-label">
Name
</div>
<div class="editor-field">
<input data-bind="value:Name" />
</div>
<div class="editor-label">
Email
</div>
<div class="editor-field">
<input data-bind="value:Email" />
</div>
<div class="editor-label">
User Type
</div>
<div class="editor-field">
<select data-bind="options: UserTypes, value: UserType, optionsCaption: 'Select User Type...'">
</select>
</div>
<p>
<button type="button" data-bind="click:SaveRegistration">Register</button>
</p>
</fieldset>
<script src="~/Scripts/knockout-2.2.1.js"></script>
<script src="~/Scripts/knockout.validation.js"></script>
<script src="~/Scripts/App/Register.js"></script>
But the GetUserTypes action is not fired.
And there is another error show in the Firebug.

Advertisement
Answer
Your action GetUserTypes doesn’t expected any parameters, but you pass viewModel object:
....
$.ajax({
url: '/Home/GetUserTypes',
type: 'post',
datatype: 'json',
data: ko.toJSON(this),
...
Try to remove this property from ajax call.
About error in FireBug, just include jQuery script in your page.