Knockout下拉列表数据绑定不能在ajax调用中工作

时间:2014-03-04 10:25:34

标签: c# javascript jquery asp.net knockout.js

我尝试使用MVC 4绑定淘汰中的下拉列表。请参阅下面的代码。

动作

    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>

但是不会触发GetUserTypes操作。

萤火虫中还有另一个错误显示。

enter image description here

请帮忙。

2 个答案:

答案 0 :(得分:1)

我认为列表没有获得数据变量。所以数据变量必须为空。

试试这个。在成功函数中添加数据参数

$.ajax({
        url: '/Home/GetUserTypes',
        type: 'post',
        datatype: 'json',
        data: ko.toJSON(this),
        contentType: 'application/json',
        success: function (data) {
            ko.mapping.fromJS(data,Register.UserTypes);
    }
});

答案 1 :(得分:1)

您的操作GetUserTypes不期望任何参数,但您传递viewModel对象:

....
$.ajax({
    url: '/Home/GetUserTypes',
     type: 'post',
     datatype: 'json',
     data: ko.toJSON(this),
     ...

尝试从ajax调用中删除此属性。

关于FireBug中的错误,只需在页面中包含jQuery脚本。