简体   繁体   English

ASP.Net MVC 5-将父子记录保存在一起

[英]ASP.Net mvc 5 - Save Parent and child records together

I am just getting started with ASP.net mvc 5 and got stuck into one problem that I have explained below: 我刚刚开始使用ASP.net mvc 5,陷入了一个我在下面解释的问题:

I have User and History models. 我有UserHistory模型。 And user can have more then one history. 用户可以拥有一个以上的历史记录。

User model: 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 model: 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 : 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);
    }
}

Here is my form: 这是我的表格:

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 : Just to remove duplication in both Create and Edit forms _Form.cshtml :仅用于删除“ Create和“ Edit表单中的重复项

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

You Have First created ViewModel. 您首先创建了ViewModel。 The view model combine to user and history model below the code 视图模型结合到代码下方的用户和历史记录模型

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

 }

second, your chtml view is modified : 其次,修改您的chtml视图:

set model userviewmodel 设置模型userviewmodel

 @model MyApp.Models.Userviewmodel

Form design change code in year, month and day 表单设计更改代码的年,月和日

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

if the add button click create new Row in the table t body every inside textbox or HiddenField Vlaue Assied the current textbox value 如果添加按钮单击表t主体中每个文本框或HiddenField Vlaue中的表t正文中的创建新行辅助当前文本框值

For example jquery function 例如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);
    });

cahnge your code in controller: 在控制器中更改代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM