【问题标题】:MVC - Update Value in Database TableMVC - 更新数据库表中的值
【发布时间】:2020-04-10 17:42:05
【问题描述】:

很长一段时间以来,我一直在尝试提出解决方案,但似乎都失败了。 我有两个表-> AssignedRoles & Incidence。在“Assignedroles”中有一个“Status”列,在创建数据时自动分配为“A”。

鉴于我的程序的性质,我想将此值从“A”更改为“C”,但从编辑方法上的“发生率”控制器更改。

以下是我尝试过的。

    public async Task<ActionResult> Edit(Incidence incidence, AssignedRoles assignedRoles)
    {
        if (ModelState.IsValid)
        {
            assignedRoles.Status = "C";
            DB.Entry(incidence).State = EntityState.Modified;

            DB.AssignedRoles.Add(assignedRoles);
            UpdateModel(assignedRoles);
            await DB.SaveChangesAsync();
            return RedirectToAction("Dashboard");
        }
        return View(incidence);
    }

下面的视图控制器显示分配给特定管理员的事件 Members() 包含来自 LoadUsersData() 的视图

    public ActionResult Members()
    {
        return View();
    }



    public ActionResult LoadUsersData()
    {
        try
        {
            var draw = Request.Form.GetValues("draw").FirstOrDefault();
            var start = Request.Form.GetValues("start").FirstOrDefault();
            var length = Request.Form.GetValues("length").FirstOrDefault();
            var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
            var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
            var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;

            int recordsTotal = 0;
            var adminUserID = Convert.ToInt32(Session["AdminUser"]);
            var rolesData = _IUsers.ShowallUsersUnderAdmin(sortColumn, sortColumnDir, searchValue, adminUserID);
            recordsTotal = rolesData.Count();
            var data = rolesData.Skip(skip).Take(pageSize).ToList();

            return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal, data = data });
        }
        catch (Exception)
        {
            throw;
        }
    }

编辑控制器

[HttpGet]
public async Task<ActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Incidence incidence = await DB.Incidences.FindAsync(id);
        if (incidence == null)
        {
            return HttpNotFound();
        }
        return View(incidence);
    }

发病率模型

public class Incidence
{
    [Key]
    public int RegistrationID { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [MaxLength(7)]
    public string TSCNO { get; set; }

    public string General { get; set; }
    public string Location { get; set; }

    [Required]
    [DataType(DataType.PhoneNumber)]
    public string Cell { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [DataType(DataType.MultilineText)]
    public string Issue { get; set; }

    public int? RoleID { get; set; }

    [DataType(DataType.MultilineText)]
    [MinLength(5,ErrorMessage ="Provide Valid Feedback")]
    public string FeedBack { get; set; }
}

AssignedRoles 模型

public class AssignedRoles
{
    [Key]
    public int AssignedRolesID { get; set; }

    public int? AssignToAdmin { get; set; }
    public int? CreatedBy { get; set; }
    public DateTime? CreatedOn { get; set; }
    public int RegistrationID { get; set; }
    public string Status { get; set; }
}

发生率编辑视图

@model CallCentre.Models.Incidence
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/AdminLTE.cshtml";
}

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.RegistrationID)

    <div class="form-group">
    @Html.LabelFor(model => model.Name, htmlAttributes: new {          @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes =   new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.TSCNO, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.TSCNO, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.TSCNO, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.General, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.General, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.General, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Cell, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Cell, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Cell, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Issue, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Issue, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Issue, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        @Html.LabelFor(model => model.FeedBack, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FeedBack, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FeedBack, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>

【问题讨论】:

  • 发病率如何与 AssignedRoles 相关联?你会展示两个模型吗?谢谢。
  • 您是否在 POST 期间获得了 incidenceassignedRoles 的值?这是我第一次看到一个帖子绑定了 2 个模型。
  • 关联表有一个允许为空的“反馈”字段。用户可以选择各种记录并从编辑操作中修改该列。我想以这样的方式实现它,当填充此字段时,表 AssignedRoles 上的“状态”从 A 更改为 C
  • 你会包括发病率模型吗?以及您的完整编辑视图(我需要查看模型声明)?谢谢
  • 谢谢一百万。它完美地工作在您的代码 sn-p 中详细说明。

标签: c# sql-server asp.net-mvc


【解决方案1】:

将您的编辑操作修改为以下代码。

// remove assignedRoles object on the parameter, we only need incidence
public async Task<ActionResult> Edit(Incidence incidence)
{
   if (ModelState.IsValid)
   {
      // we need to select the assignedRole from that RegistrationId
      var role = db.AssignedRoles.FirstOrDefault(a=>a.RegistrationID == incidence.RegistrationID)
      role.Status = "C";

      DB.Entry(incidence).State = EntityState.Modified;

      // you're just editing the assignedRole right? no need to add a new one. Comment out or remove the code below
      // DB.AssignedRoles.Add(assignedRoles);
      // UpdateModel(assignedRoles);

      await DB.SaveChangesAsync();
      return RedirectToAction("Dashboard");
   }
   return View(incidence);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 2014-11-22
    • 1970-01-01
    • 2018-10-15
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多