Nickson
Nickson

Reputation: 135

MVC - Update Value in Database Table

I have been trying to come up with a solution for quite some time now but they all seem to fail. I have two tables -> AssignedRoles & Incidence. Within the "Assignedroles" there is a "Status" Column that is auto-assigned "A" upon creation of data.

Given the nature of my program, i would like to change this value from "A" to "C" but from the "Incidence" Controller on the Edit Method.

Below is what i have tried.

    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);
    }

The View Controller below displays Incidences allocated to the specific admin The Members() contains the View from 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;
        }
    }

The Edit Controller

[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);
    }

Incidence Model

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 Model

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; }
}

Incidence Edit View

@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>

Upvotes: 1

Views: 1033

Answers (1)

Jerdine Sabio
Jerdine Sabio

Reputation: 6130

Modify your edit action to the code below.

// 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);
}

Upvotes: 2

Related Questions