MVC3 Text Box Text change Event

2019-08-27 18:55发布

问题:

I have the following scenario, using mvc3:

I have a database table which holds a RecordID, RecordName and RecordType. Displayed are three text boxes, one for each of the fields mentioned previously.

My Question is, when i enter a RecordID into the relevant text box, i want to be able to show the RecordName and RecordType for that particular RecordID. How can i achieve this?

回答1:

In View:

@Html.TextBoxFor(model => model.RecordId)
@Html.TextBoxFor(model => model.RecordName)
@Html.TextBoxFor(model => model.RecordType)

<script language="javascript">
$('#RecordId').change(function(){
    var recordId = this.value;
    $.getJSON("/MyController/GetRecordById",
        {
            id: recordId
        },
        function (data) {
            $('RecordName').val(data.Name);
            $('RecordType').val(data.Type);
        });
});
</script>

In Controller:

public JsonResult GetRecordById(int id)
{
    var record = recordRepository.GetById(id);
    var result = new {
                         Name = record.Name,
                         Type = record.Type
                     }

    return Json(result, JsonRequestBehavior.AllowGet);
}