MVC5父子单一编辑表格

时间:2015-08-14 14:22:08

标签: c# asp.net-mvc entity-framework datamodel

我正在尝试使用单页进行编辑并使用父数据和子数据创建记录。

像添加员工记录的页面一样,以及他的经验列表。 示例:enter image description here

除非用户在编辑页面中删除第一个子记录,否则工作正常。

  • 当我们在编辑模式下打开页面并添加新体验时,它很好。
  • 当我们在编辑模式下打开页面,并删除索引4,5或任何非0的体验记录时,它很好
  • 当我们在编辑模式下打开页面,并删除索引0处的体验记录时,会生成错误,说经验为空

员工的控制器代码:

public class EmployeeController : Controller
{
    private DBEntities db = new DBEntities();

    // GET: Employee/Create
    public ActionResult Create()
    {
        ViewBag.caste_id = new SelectList(db.tbl_caste, "caste_id", "caste_name");
        ViewBag.emp_grade = new SelectList(db.tbl_grade, "grade_id", "grade_title");
        ViewBag.emp_position_title = new SelectList(db.tbl_position, "id", "position");
        ViewBag.emp_project_name = new SelectList(db.tbl_project, "id", "project_name");
        return View();
    }


    // POST: Employee/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(employee employee)
    {
        if (ModelState.IsValid)
        {
            db.employee.Add(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.caste_id = new SelectList(db.tbl_caste, "caste_id", "caste_name", employee.caste_id);
        ViewBag.emp_grade = new SelectList(db.tbl_grade, "grade_id", "grade_title", employee.emp_grade);
        ViewBag.emp_position_title = new SelectList(db.tbl_position, "id", "position", employee.emp_position_title);
        ViewBag.emp_project_name = new SelectList(db.tbl_project, "id", "project_name", employee.emp_project_name);
        return View(employee);
    }

    // GET: Employee/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        employee employee = db.employee.Find(id);
        if (employee == null)
        {
            return HttpNotFound();
        }
        ViewBag.caste_id = new SelectList(db.tbl_caste, "caste_id", "caste_name", employee.caste_id);
        ViewBag.emp_grade = new SelectList(db.tbl_grade, "grade_id", "grade_title", employee.emp_grade);
        ViewBag.emp_position_title = new SelectList(db.tbl_position, "id", "position", employee.emp_position_title);
        ViewBag.emp_project_name = new SelectList(db.tbl_project, "id", "project_name", employee.emp_project_name);
        return View(employee);
    }

    // POST: Employee/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(employee employee)
    {
        if (ModelState.IsValid)
        {
            //For some reason children are brought in with Parent_Id = null.
            //Manually resetting it fixes this issue.
            //Needs to be set before parent = modified for referential integrity
            int cnt = 0;
            if(employee.tbl_experience != null)
            {
                foreach (var c in employee.tbl_experience)
                {
                    c.employeeid = employee.employeeid;
                    if (!(c.exp_id > 0))
                    {
                        c.exp_id = cnt;
                        cnt--;
                    }
                }
            }
            db.Entry(employee).State = EntityState.Modified;

            //Remove deleted child
            //employee.tbl_experience.Where(m => m.).ToList().ForEach(m => p.Children.Remove(m));
            List<tbl_experience> childToDelete = db.tbl_experience.Where(item => item.employeeid == employee.employeeid).ToList();
            foreach (var item in childToDelete)
            {
                if (employee.tbl_experience.IndexOf(item) > 0)
                {
                    db.Entry(item).State = EntityState.Deleted;
                }
            }
            //db.Entry(childToDelete).State = EntityState.Deleted;

            for (int i = 0; i < employee.tbl_experience.Count; i++)
            {

                    db.Entry(employee.tbl_experience[i]).State = employee.tbl_experience[i].exp_id > 0 ? EntityState.Modified : EntityState.Added;
                //}
            }
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        ViewBag.caste_id = new SelectList(db.tbl_caste, "caste_id", "caste_name", employee.caste_id);
        ViewBag.emp_grade = new SelectList(db.tbl_grade, "grade_id", "grade_title", employee.emp_grade);
        ViewBag.emp_position_title = new SelectList(db.tbl_position, "id", "position", employee.emp_position_title);
        ViewBag.emp_project_name = new SelectList(db.tbl_project, "id", "project_name", employee.emp_project_name);
        return View(employee);
    }
}

编辑视图代码:

@model App.Models.employee

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>


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

    <div class="form-horizontal">
        <h4>employee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.employeeid)

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

        <div class="form-group">
            @Html.LabelFor(model => model.emp_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emp_name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emp_name, "", 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 class="form-group">
            <div class="col-md-12">
    <h3>Experience List <input type="button" value="add" id="addExp" /></h3>
    <table class="table">
        <tr>
            <th>@Html.LabelFor(model => model.tbl_experience.ElementAt(0).exp_organization)</th>
            <th>@Html.LabelFor(model => model.tbl_experience.ElementAt(0).exp_position)</th>
            <th>@Html.LabelFor(model => model.tbl_experience.ElementAt(0).exp_fromyear)</th>
            <th>@Html.LabelFor(model => model.tbl_experience.ElementAt(0).exp_toyear)</th>
            <th>&nbsp;</th>
        </tr>
            @for (int i = 0; i < Model.tbl_experience.Count; i++)
            {
                <tr class="item">
                    <td>
                        @Html.HiddenFor(model => model.tbl_experience.ElementAt(i).exp_id, new { @Name = string.Format("tbl_experience[{0}].exp_id", i) })
                        @Html.TextBoxFor(model => model.tbl_experience.ElementAt(i).exp_organization, new { @Name = string.Format("tbl_experience[{0}].exp_organization", i) })
                        @Html.ValidationMessageFor(model => model.tbl_experience.ElementAt(i).exp_organization)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.tbl_experience.ElementAt(i).exp_position, new { @Name = string.Format("tbl_experience[{0}].exp_position", i) })
                        @Html.ValidationMessageFor(model => model.tbl_experience.ElementAt(i).exp_position)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.tbl_experience.ElementAt(i).exp_fromyear, new { @Name = string.Format("tbl_experience[{0}].exp_fromyear", i) })
                        @Html.ValidationMessageFor(model => model.tbl_experience.ElementAt(i).exp_fromyear)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.tbl_experience.ElementAt(i).exp_toyear, new { @Name = string.Format("tbl_experience[{0}].exp_toyear", i) })
                        @Html.ValidationMessageFor(model => model.tbl_experience.ElementAt(i).exp_toyear)
                    </td>
                    <td>
                        <a href="#" class="rem">Delete</a>
                    </td>
                </tr>
            }
        <tbody id="expTable">

        </tbody>
    </table>
        </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        last = @Model.tbl_experience.Count;
        $('#addExp').click(function () {
            var newRow = '<tr class="item"><input type="hidden" name="tbl_experience[' + last + '].exp_id" value="0">';
            newRow += '<td class="col"><input type="text" name="tbl_experience[' + last + '].exp_organization"></td>';
            newRow += '<td class="col"><input type="text" name="tbl_experience[' + last + '].exp_position"></td>';
            newRow += '<td class="col"><input type="text" name="tbl_experience[' + last + '].exp_fromyear"></td>';
            newRow += '<td class="col"><input type="text" name="tbl_experience[' + last + '].exp_toyear"></td>';
            newRow += '<td class="col"><a href="#" class="rem">Rem</a></td>';
            newRow += '</tr>';

            $('#expTable').append(newRow);
            last++;
        });
        $(document).on('click', '.item .rem', function (e) {
            //console.log('removed');
            e.preventDefault();
            $(this).closest('.item').remove();
        });

    </script>
}

0 个答案:

没有答案