使用EF更新单个字段

时间:2018-01-11 11:34:07

标签: entity-framework

我需要更新单个字段' status'使用EF ..

查看:

@model IEnumerable<DemoUserMeetings.Models.Meeting>

@{
ViewBag.Title = "Index";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<table class="table">

<tr>
    <th>@Html.DisplayNameFor(m => m.MeetingFromId)</th>
    <th>@Html.DisplayNameFor(m => m.MeetingToId)</th>
    <th>@Html.DisplayNameFor(m => m.MeetingStartTime)</th>
    <th>@Html.DisplayNameFor(m => m.MeetingEndTime)</th>
    <th>@Html.DisplayNameFor(m => m.MeetingStatus)</th>
    <th>@Html.DisplayNameFor(m => m.MeetingDescription)</th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.MeetingFromId)</td>
        <td>@Html.DisplayFor(modelItem => item.MeetingToId)</td>
        <td>@Html.DisplayFor(modelItem => item.MeetingStartTime)</td>
        <td>@Html.DisplayFor(modelItem => item.MeetingEndTime)</td>
        <td>@Html.DisplayFor(modelItem => item.MeetingStatus)</td>
        <td>@Html.DisplayFor(modelItem => item.MeetingDescription)</td>

        <td>
            <input type="button" class="btn btn-default btnAccept" value="Delete" id="@item.MeetingId" />
        </td>
    </tr>
}

<a href="@Url.Action("Index","Home")">Logout</a>

<script type="text/javascript">

$('.btnAccept').click(function () {

    var update_id = $(this).attr('id');
    var isTrue = confirm("Accept meeting invite?");

    if (isTrue) {
        $.ajax({

            url: '@Url.Action("AcceptMeeting","Home")',
            type: 'POST',
            data: { id: update_id },
            success: function () {
                alert('success');
            },
            error: function () {
                alert('failed');
                return false;
            }
        });
    } else {
        return false;
    }
});

</script>

控制器:

[HttpPost]
    public ActionResult AcceptMeeting(int id)
    {
       // Here i need to set status ="Accept" for particular id
        return View();
    }

这就是我尝试过的,我想更新会议的状态,以及#34;接受&#34;。我知道这不是一件大事,但我是EF的新手。我得到了控制器会议的ID,但不知道进一步的过程。任何想法?

1 个答案:

答案 0 :(得分:0)

试试这个

using (var db = new YourDBContext())
  {
    var meeting= context.Meeting.Find(id);
    meeting.MeetingStatus = true;
    db.Meeting.Attach(meeting);
    db.SaveChanges();
  }