0

我在 ASP.NET MVC3 中编写了一个表单,我无法获取条目来保存我在数据库中所做的更改,但是在调试时,我注意到这些更改反映在数据上下文中。我在运行此代码时没有遇到任何错误。如果您需要更多,请告诉我。谢谢!

控制器

[HttpPost]
    public ActionResult Edit(Tool tool, FormCollection collection)
    {
        if (collection["Tool.Person.PersonID"] != "")
        {
            tool.Person= context.People.Find(
                 Convert.ToInt32(collection["Tool.Person.PersonID"])
            );
        }
        if (collection["Tool.Company.CompanyID"] != "")
        {
            tool.Company = context.Companies.Find(
                 Convert.ToInt32(collection["Tool.Company.CompanyID"])
            );
        }

        if (ModelState.IsValid)
        {
            context.Entry(tool).State = EntityState.Modified; 
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(tool);
    }

前两个if语句检查用户是否输入了个人或公司,信息通过 FormCollection 传递。PersonID 和 CompanyID 分别是 Person 和 Company 的主键。我多次逐行执行该方法并获得相同的结果 - 在 context.SaveChanges(); 之后,上下文反映了更改,但 Person_PersonID 和 Company_CompanyID 的数据库条目仍然为空。

4

1 回答 1

1

在用户提交表单后尝试使用视图模型并访问数据库。

这应该会让你顺利上路。

视图模型

using System.ComponentModel.DataAnnotations;

namespace Project.ViewModels
{
    public class _tools
    {
        [Required(ErrorMessage="ToolID is required")]
        public int32 ToolID{ get; set; } //whatever ID you use to retrieve the Tool from the database.

        [Required(ErrorMessage="PersonID is required")]
        public int32 PersonID{ get; set; }

        [Required(ErrorMessage="CompanyID is required")]
        public int32 CompanyID{ get; set; }
    }

}

控制器岗位

[HttpPost]
public ActionResult Edit(_tool viewModel)
{

    if (ModelState.IsValid)
    {
        Tool tool = db.GetTool(viewModel.ToolID) //whatever method you use to get a current version of the row.  You already do this before you send the data to the client, so just copy that code

        tool.Person = viewModel.PersonID
        tool.Company = viewModel.CompanyID

        context.Entry(tool).State = EntityState.Modified; 
        context.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(tool);
}

看法

@model = _tool

@using(Html.BeginForm("Edit", "ControllerNameHere", FormMethod.Post, null))
{
    @Html.HiddenFor(model => model.ToolID)
    @*Also add whatever inputs you use to get PersonID and CompanyID from the user.
      Make sure to either use the @Html helpers or to give them names that correspond.
      i.e. name one input PersonID and the other CompanyID*@

    <input type="submit" value="Edit">

}
于 2012-08-02T22:09:38.743 回答