用于更新表行数据的控制器动作方法

时间:2017-11-09 12:11:45

标签: jquery json asp.net-mvc entity-framework asp.net-ajax

sample of my project: 正如你在图片中看到的,我试图实现编辑服务,一旦单击编辑,调用onClick函数调用的modal.show方法GetbyID:

 function getbyID(ID) {
     $('#Name').css('border-color', 'lightgrey');
     $('#College').css('border-color', 'lightgrey');
     $.ajax({
         url: '@Url.Action("GetbyID")'+'?ID='+ID  ,
         type: "GET",
         contentType: "application/json;charset=UTF-8",
         dataType: "json",
         success: function (result) {

             $('#Name').val(result.Name);
             $('#College').val(result.College);
             $('#myModal').modal('show');
             $('#btnUpdate').show();
             $('#btnAdd').hide();
         },
         error: function (errormessage) {
             alert(errormessage.responseText);
         }
     });
     return false;
 }

The Edit modal picture:

单击更新时,单击update()调用:

 function Update() {

     var student = {
         Name: $('#Name').val(),
         College: $('#College').val(),

     };
     $.ajax({
         url: '@Url.Action("Update")',
         data: JSON.stringify(student),
         type: "POST",
         contentType: "application/json;charset=utf-8",
         dataType: "json",
         success: function (result) {
             LoadData();
             $('#myModal').modal('hide');
             $('#Name').val("");
             $('#College').val("");

         },
         error: function (errormessage) {
             alert(errormessage.responseText);
         }
     });
 }

在控制器中实现更新操作方法的正确方法是什么:

  // Update student.
    public JsonResult Update(Student student )
    {
    //What to insert here to update the data in the database...?

    }

2 个答案:

答案 0 :(得分:1)

var objstudent = db.student.where( m => m.ID == student.ID).firstorDefault();
if(objstudent != null)
{
    objstudent.Name = student.Name;
    objstudent.College = student.College;
    db.Savechanges();
}

答案 1 :(得分:0)

由于您使用EF,您可以执行以下操作:

using (var db = new YourContext())
{
    var result = db.Students.SingleOrDefault(s => s.Id== student.Id);
    if (result != null) // if result is null then there is no student in the db with that id 
    {
        result.Name = student.Name;
        result.College = student.College;
        db.SaveChanges();
    }
    else
    {
    //perform an insert instead
    }
}