我试着用MVC 4绑定knockout中的下拉列表。下面是我的代码:
操作
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);
}
}
敲除.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>
但不会触发GetUserTypes操作。
Firebug中显示了另一个错误。
2条答案
按热度按时间3lxsmp7m1#
您的操作
GetUserTypes
不需要任何参数,但您传递了viewModel对象:尝试从 AJAX 调用中删除此属性。
关于FireBug中的错误,只需在您的页面中包含jQuery脚本。
mbskvtky2#
我认为列表没有到达数据变量。所以数据变量必须为空。
试试这个。在success函数中添加数据参数