如何在选项中显示属性,但在选中时获取id

时间:2017-10-02 05:20:42

标签: c# knockout.js

这是我的学生班(简化)

public class Student
{
    public int StudentId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

我有一个对象集合:

public JsonResult FetchSample()
{
    List<Students> students = StudentDataAccess.GetList();

    return Json(students, JsonRequestBehavior.AllowGet); //this will be loaded in students ko.observableArray([])
}

我使用knockoutjs viewmodel来获取选项的学生列表。但是我怎样才能显示LastName +&#34;,&#34; + FirstName但是当我选择一个项目时,它会获得StudentId吗?

这是我的knockoutjs viewmodel:

$(function() {
    ko.applyBindings(studVm);
    studVm.GetStudents();

});

var studVm =
{
    students: ko.observableArray([]),
    studentSelected: ko.observable(),
    GetStudents: function () {
        var self = this;
        $.ajax({
            url: '/OB/FetchSample',
            type: 'GET',
            dataType: 'json',
            data: ko.toJSON(this),
            contentType: 'application',
            success: function (data) {
                //  self.students.push(data);
                self.students(data);
            }
        });
    }
}

这是我的HTML

    <p>
        Student:
        <select data-bind="options: students, optionsCaption: 'Select student', value: studentSelected"></select>
    </p>

<button type="submit">SAVE</button>

更新:

我添加了按钮元素:SAVE。单击“保存”后,将触发此ActionResult方法:

public ActionResult FilePayment(Payment payment)
{
    PaymentContext db = new PaymentContext();
    Payment newPay = new Payment();

    newPay.StudentId = payment.StudentId; //this should be from the selected drop down list
    newPay.PayPrice = payment.PayPrice; //I just omitted the html element for this.

    db.Paymnents.Add(newPay);
    db.SaveChanges();
    return View();
}

1 个答案:

答案 0 :(得分:0)

首先,您必须创建与您的服务器端Student类匹配的客户端Student类(我将其称为子视图模型)。请注意,客户端Student类必须具有fullName属性,如下所示。

function Student(id, fName, lName) {
    this.studentId = id;
    this.firstName = fName;
    this.lastName = lName;
    this.fullName = fName + ' ' + lName;
}

第二次,编辑ajax成功回调以创建Student数组,如下所示。

success: function (data) {
    for (var i = 0; i < data.length; i++) {
        // please pay attention at the UPPER case/lower case below, it could be data[i].StudentId depends on your server JSON converter setting
        var student = new Student(data[i].studentId, data[i].lastName, data[i].firstName);
        self.students.push(student);
    }
}

上次,编辑您的绑定,如下所示。

<select data-bind="options: students, optionsText: 'fullName', optionsValue: 'id', value : studentSelected"></select>

我在这里创建了一个CodePen https://codepen.io/trgiangvp3/pen/veJryp