ASP.Net mvc 5 - 将父级和子级记录保存在一起

时间:2017-07-25 11:35:30

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

我刚开始使用ASP.net mvc 5并遇到了一个我在下面解释过的问题:

我有UserHistory个型号。用户可以拥有多个历史记录。

User型号:

public class User
{
    public int ID { get; set; }
    public string TicketType { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }

    public virtual ICollection<History> Histories { get; set; }
}

History型号:

public class History
{
    public int ID { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }

    public virtual User User { get; set; }
}

UserController

public class UsersController : Controller
{
    private MyDbContext db = new MyDbContext();

    public ActionResult Create()
    {
        var user = new User();
        user.Histories = new List<History>();
        user.Histories.Add(new History { });
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,TicketType,FirstName,LastName")] User user)
    {
        if (ModelState.IsValid)
        {
            db.Users.Add(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(user);
    }
}

这是我的表格:

Create.cshtml

@model MyApp.Models.User

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

    @Html.Partial("_Form")

    <input type="submit" value="Create" class="btn btn-lg btn-success" />
}

_Form.cshtml:仅删除CreateEdit表单中的重复

        @model MyApp.Models.User
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.TicketType, htmlAttributes: new { @class = "control-label" })
            @Html.DropDownListFor(model => model.TicketType, new List<SelectListItem>
                    {
                        new SelectListItem() {Text = "OPD", Value="opd"},
                        new SelectListItem() {Text = "Emergency", Value="emergency"},
                    }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.TicketType, "", new { @class = "text-danger" })
        </div>

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

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


        <!-- TODO: fix these form elements which are 
         related to History not User. I am not sure how to do that. 
         Also NOTE that, user fields are saving properly and 
         update is also working. -->


        <div class="form-group">
            <label class="control-label">Year</label>
            <input type="text" value="" class="form-control" />
        </div>

        <div class="form-group">
            <label class="control-label">Month</label>
            <input type="text" value="" class="form-control" />
        </div>

        <div class="form-group">
            <label class="control-label">Day</label>
            <input type="text" value="" class="form-control" />
        </div>

1 个答案:

答案 0 :(得分:1)

您首先创建了ViewModel。 视图模型与用户和历史模型相结合 在代码下面

Public class userviewmodel
{

     public string TicketType { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string Gender { get; set; }         
     public int Year { get; set; }
     public int Month { get; set; }
     public int Day { get; set; }

 }

第二,你的chtml视图被修改:

设置模型userviewmodel

 @model MyApp.Models.Userviewmodel

年,月,日的表单设计更改代码

  <Table>
    <thead> 
       <tr>
          <td>Year</td>
          <td>Month</td>
          <td>Day</td>
       </tr>
      </thead>
      <tbody id="tbodyval">
      </tbody>
    </table>


<div class="form-group">
        <label class="control-label">Year</label>
        @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })
 </div>

 <div class="form-group">
    <label class="control-label">Year</label>
    @Html.EditorFor(model => model.month, new { htmlAttributes = new { @class = "form-control" } })
 </div>

 <div class="form-group">
    <label class="control-label">Year</label>
    @Html.EditorFor(model => model.day, new { htmlAttributes = new { @class = "form-control" } })
  </div>
  <input type="button" value="add">

如果添加按钮单击表t body中的create new row 每个内部文本框或HiddenField Vlaue都会确定当前文本框值

例如  jquery函数

  $("#add").click(function(){
      string row="<tr><td><input type='text' value='$('#year').val(), 
       name='Yearlist'></td>
        <td><input type='text' value='$('#month').val(), name='monthlist'></td>
       <td><input type='text' value='$('#day').val(), name='daylist'></td>
          </tr>"
        $("#tbodyval").append(row);
    });

在控制器中修改你的代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( Userviewmodel usermodel, string[] yearList,string[] monthList,string[] dayList())
{
    if (ModelState.IsValid)
    {

        user model=new user()
        model.TicketType=.usermodel.TicketType;
        model.FirstName=usermodel.FirstName;
        model.LastName=usermodel.LastName;
        model.Gender=usermodel.Gender;

       for(int i=0;i<yearlist.count();i++)
       {
         History child=new History()  

         child.Year=yearlist[i].Year;
         child.month=montList[i].month;
         chile.day=dayList[i].day;            
         model.Histories.add(child);  
       }                      

        db.Users.Add(model);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(user);
}