使用ViewModel添加模型的多个实例

时间:2015-12-13 22:32:29

标签: c# jquery asp.net asp.net-mvc

我有模型Event和Ticket

public class Event
{
    public int EventID { get; set; }
    [Required]
    public String Name { get; set; }
    [Required]
    public String Location { get; set; }

    [Required]
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }
    [Required]
    [DataType(DataType.MultilineText)]
    public String Description { get; set; }
    [Required]
    public int TicketsAvailable { get; set; }
    //navigation property
    public virtual ICollection<Order> Order { get; set; }
    //navigation property
    public virtual ICollection<Ticket> Ticket { get; set; }
}

public class Ticket
{
   public int TicketID { get; set; }
   [Required]
   [ForeignKey("Event")]
   //foreign key
    public int EventID { get; set; }
   [Required]
   public string Description { get; set; }
   [Required]
   public float Price { get; set; }
    //navigation property
    public virtual Event Event { get; set; }
    //navigation property
    public ICollection<OrderDetails> OrderDetails { get; set; }
}

我创建了两个View Models,允许我为每个Event添加多个Tickets

public class TicketVm
{
    [Required]
    public string Description { get; set; }
    [Required]
    public float Price { get; set; }
}

public class CreateTicketVm
{
    public int EventId { get; set; }
    public List<TicketVm> Tickets { set; get; }
}

然后我有一个允许用户创建新事件的视图。然后,当他们提交此事件时,他们将被定向到CreateTicket View,该视图应该使用与创建事件相同的EventID为此事件添加新票证。

这是我的创建故障单视图

@model Site.Models.CreateTicketVm

<head>
<title>Create Event Tickets</title>
<link href="Content/TicketStyles.css" rel="stylesheet" type="text/css">
</head>


<h3> Tickets</h3>
<div id="tickets"></div>
@Html.HiddenFor(s => s.EventId)

<input type="button" id="add" value="Add Ticket" />
<input type="submit" id="btnSave" />

@section scripts{
<script>
$(function () {
    //Lets create the first row
    addNewRow();

    $("#add").click(function (e) {
        e.preventDefault();
        addNewRow();
    });

    $("#btnSave").click(function (e) {
        e.preventDefault();

        var createTicket = { EventId: $("#EventId").val(), Tickets: [] };
        var rows = $("#tickets").find(".item");

        $.each(rows, function (i, row) {
            var _row = $(this);

            var inputs = _row.find("input");
            var ticket = {};
            $.each(inputs, function (index, item) {
                var _this = $(this);
                ticket[_this.data("for")] = _this.val();
            });
            createTicket.Tickets.push(ticket);
        });

        var targetUrl = "@Url.Action("CreateTicket","Tickets1")";
        $.ajax({
            url: targetUrl,
            contentType: "application/json",
            data: JSON.stringify(createTicket),
            type: "POST"
        }).done(function (res) {
            if (res.Status === "Success") {
                window.location.href = "@Url.Action("Success")";
            }
        });
    });
});

function addNewRow() {
    $.get("@Url.Action("AddNewTicketRow","Tickets1")", function (res) {
        $("#tickets").append(res);
    });
}
</script>
}

这是我的AddNewTicket局部视图

@model Site.Models.TicketVm
<div class="item">
    @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div>
    @Html.TextBoxFor(model => model.Description, new { @data_for = "Description" })
</div>

@Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })
<div>
    @Html.TextBoxFor(s => s.Price, new { @data_for = "Price" })
</div>
</div>

这是我的Tickets1Controller类

 public class Tickets1Controller : Controller
 {
    private ApplicationDbContext db = new ApplicationDbContext();


    public ActionResult CreateTicket(int id)
    {

        var vm = new CreateTicketVm { EventId = id };
        return View(vm);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateTicket(CreateTicketVm model)
    {
        if (model != null)
        {

            foreach (var ticketVm in model.Tickets)
            {
                db.Tickets.Add(new Ticket{ EventID = model.EventId, 
                 Description=ticketVm.Description, Price =ticketVm.Price});
                db.SaveChanges();

            }
            return RedirectToAction("Index");

        }
        return RedirectToAction("Index");  
    }

    public ActionResult AddNewTicketRow()
    {
        var vm = new TicketVm();
        return    PartialView("~/Views/Tickets1/Partials/AddNewTicketRow.cshtml", vm);
    }

我的门票没有保存,我不明白为什么因为EventID被传递到CreateTicket视图但是当点击提交按钮并且门票没有保存到我的数据库表时没有任何反应。任何有关如何解决此问题的建议都将非常感谢。

1 个答案:

答案 0 :(得分:0)

一旦我遇到同样的问题。我做的是为页面定义一个jquery变量并且每次都增加它#34; AddNewTicketRow&#34;单击并将其作为参数发送到&#34; AddNewTicketRow&#34;控制器并使用它作为INDEX创建AddNewTicket局部视图,如下所示:

@Html.TextBoxFor(M => M.Description, new { Name = "Tickets[" + @Model.Index + "].Description", id = "Tickets[" + @Model.Index + "].Description" })

@Html.TextBoxFor(M => M.Price, new { Name = "Tickets[" + @Model.Index + "].Price", id = "Tickets[" + @Model.Index + "].Price" })