简体   繁体   English

在视图MVC5之间传递值

[英]Passing values between views MVC5

I am creating an event management system and I want to create an event and then create multiple tickets for this event. 我正在创建一个事件管理系统,并且想要创建一个事件,然后为此事件创建多个票证。 I am using c# and ASP.NET MVC. 我正在使用c#和ASP.NET MVC。 I have created these model classes; 我已经创建了这些模型类。

public class Event
{
    public int EventID { get; set; }
    [Required]
    public String Name { get; set; }
    [Required]
    public String Location { get; set; }
    [Required]
    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; }
}

I have used the Scaffolded CRUD views for the events and then I want to pass the EventID for the event I create to the AddTicket view and create new tickets specific to the event. 我已将脚手架CRUD视图用于事件,然后将创建的事件的EventID传递到AddTicket视图,并创建特定于事件的新票证。 Here is my controller class; 这是我的控制器类;

public class Events1Controller : Controller
{
    private IEventRepository _eventRepository;
    private ITicketRepository _ticketRepository;

    public Events1Controller()
    {
    this._eventRepository = new EventRepository(new ApplicationDbContext());
    this._ticketRepository = new TicketRepository(new ApplicationDbContext());
    }

    // GET: Events
    [AllowAnonymous]
    public ActionResult Index()
    {

        return View(_eventRepository.GetEvents());
    }
// GET: Events/Create
    [AllowAnonymous]
    public ActionResult Create()
    {
        return View();
    }

    // POST: Events/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]
    [AllowAnonymous]
    public ActionResult Create([Bind(Include = "EventID,Name,Location,Date,Description,TicketsAvailable")] Event @event)
    {
        if (ModelState.IsValid)
        {
            Session["Event1"] = @event;
            _eventRepository.InsertEvent(@event);

            return RedirectToAction("SaveTickets");
        }

        return View();
    }

    [AllowAnonymous]
    public ActionResult SaveTickets()
    {           
        Event @e1 = Session["Event1"] as Event;
        Ticket @ticket1 = new Ticket
        {
            EventID = @e1.EventID
        };

        return View(@ticket1);

    }



 // POST: Events/AddToTickets
    [HttpPost]
    [ValidateAntiForgeryToken]
    [AllowAnonymous]
    public ActionResult AddToTickets([Bind(Include = "TicketID, EventID,    Description, Price")] Ticket @ticket)
    {

        if (ModelState.IsValid)
        {
            _ticketRepository.InsertTicket(@ticket);
            return RedirectToAction("Index");
        }
        return View();
    }




<h2>Create</h2>

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

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


    <div class="form-group">
        @Html.LabelFor(model => model.EventID, htmlAttributes: new { @class    = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DisplayFor(model => model.EventID, new { htmlAttributes =   new { @class = "form-control" } })

        </div>
    </div>

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



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




    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="AddToTickets" class="btn btn-default" />

        </div>
    </div>
</div>
}

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

</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

I have used forms within my razor views and the events are saving to the database correctly, and the EventID is being set in the Ticket and passed to the SaveTicket view. 我在剃刀视图中使用了表单,并且事件已正确保存到数据库,并且在工单中设置了EventID并将其传递到SaveTicket视图。 However the problem occurs when I try and save the ticket, the ticket does not save and the page simply refreshes. 但是,当我尝试并保存故障单时,便会出现问题,故障单不会保存,页面只会刷新。 I have tried many tutorial but none have provided me with a solution yet and I have been stuck for the best part of a week. 我已经尝试了许多教程,但是都没有为我提供解决方案,而且我在一周的最佳时间里一直处于困境。

Your problem may be that you're not telling your <form> where to post the data. 您的问题可能是您没有告诉<form>将数据发布到何处。

When you just use @using (Html.BeginForm()) it assumes you want to post the data back to the same url that the view came from, or what's in the address bar. 当您仅使用@using (Html.BeginForm())它假定您要将数据发回到视图所来自的相同URL或地址栏中。

Since the action that returns the view is SaveTickets then the data will be posted to http://host/Events1/SaveTickets but your [HttpPost] action is AddToTickets . 由于返回视图的操作为SaveTickets因此数据将发布到http://host/Events1/SaveTickets但是您的[HttpPost]操作为AddToTickets

You can either rename your [HttpPost] action to SaveTickets as well, which would be easiest, or tell your form what the url/action is that you want to post to. 您也可以将[HttpPost]操作重命名为SaveTickets (这是最简单的),也可以告诉表单要发布到的URL /操作是什么。

@using (Html.BeginForm("AddToTickets","Events1"))

This might solve the problem, but you want to take Stephen's advice and create a seperate controller for Tickets.. 这可能会解决问题,但是您要听取Stephen的建议,并为Tickets创建一个单独的控制器。

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

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