Transferring data between views in MVC5

Currently in the process of developing an event management system where I need to create events and generate multiple tickets for each event. Utilizing c# and ASP.NET MVC, I have set up the following 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; }
}

Initially used Scaffolded CRUD views for the events and am currently faced with a challenge on how to pass the EventID for a newly created event to the AddTicket view in order to create event-specific tickets. Below is a snippet from 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();
    }

    ...

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

Having incorporated forms within my razor views, successfully saving events into the database with correct EventIDs being passed to tickets displays correctly in the SaveTicket view. However, hitting a roadblock when attempting to save the ticket as it fails and the page simply reloads. Numerous tutorials have been explored without resolving the issue, leaving me stuck for quite some time now.

Answer №1

If you're encountering issues, it could be due to not specifying where your <form> should post the data.

When using @using (Html.BeginForm()), it automatically assumes that you want to post the data back to the same URL as the view or what's displayed in the address bar.

In this case, since the initial action is SaveTickets, the data will be posted to http://host/Events1/SaveTickets, but your [HttpPost] action is named AddToTickets.

To resolve this, consider renaming your [HttpPost] action to

SaveTickets</code for consistency, or explicitly define the URL/action in your form.</p>

<pre><code>@using (Html.BeginForm("AddToTickets","Events1"))

This approach might help address the issue, although following Stephen's suggestion to create a separate controller for Tickets would also be beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to showcase a location on a map

Seeking a method to visually represent users' locations on a world map using HTML, JavaScript, or any other suitable approach. The data will be extracted from an Excel file and consists of the City Name only. Each user's location should be marked ...

Exploring the implementation of window.addEventListener within an Angular project

I am currently working on testing a method in Angular using Jasmine. However, I am running into an issue with triggering the mouse event (specifically when the browser back button is clicked). Below is the code snippet I'm working with: navigate() { ...

Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge. const example = { myFunction(){ console.log(this); }, myFunction2(){ function myFunction3(){ console.log(this) } return ...

Split Screen Text Comparisons

For some reason, I am finding it challenging to display two paragraphs side by side without disrupting the overall layout. If you would like a visual explanation of the issue, please check out this video: Video If you're interested in reviewing the c ...

Issues with NodeJs Express routes execution

After testing, I found that only the default route "/" is working in my code. Many similar issues involve routers being mounted to paths like "/auth" or "/user". Even when I tested the default router mounted to "/", it still isn't functioning properly ...

While attempting to import modules in Visual Studio Code, an error message appears stating "Unexpected token {"

Greetings! I am currently using Visual Code to run my project and would like to share my code with you. In the file external.js: export let keyValue=1000; In the file script.js: import {keyValue} from './external.js'; console.log(keyValue); ...

Combining Mouseover and Click Events in Vue JS

Having four pictures, I want to display a specific component when hovering over them. However, I also need to bind the click event so that clicking on the picture will reveal the component. The challenge is that I am unable to simultaneously bind two event ...

If someone installs our chat widget on their website using an <iframe> script, I would like the widget to be deactivated when our website is experiencing downtime

We utilize an iframe to create our Chat Widget. One issue we face is that when our main website is down, it causes errors on client websites where the widget is embedded. I am looking for a way to automatically disable the "Chat widget" when our website ...

getting information from component in NextJS

Apologies if this question is too basic. I recently started my journey into learning React and NextJS. I am working on a simple application that fetches data and displays it on the Home page. In my component file, I have two functions. This component file ...

Enhanced dropdown menu with Vue.js

Trying to manage two select lists where their combined values equal a maximum size. For example, if the max number of people is 20 and 5 children are selected, only a maximum of 15 adults can be added, and so on. My latest attempt: Template: <div cla ...

When using $resource.save, it returns a "Resource" instead of just an ID

For some reason, I am struggling with a seemingly simple task and cannot find a solution by going through documentation or other Angular related questions on SO. I may not be the brightest, so I could really use some help here as I am feeling stuck. Take ...

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

What's the most efficient method of exporting modules along with their submodules in (Vue, React)?

Looking for the most efficient method to export a module that contains submodules with the help of an index.js? I have been following a specific naming and saving convention for my web components in projects involving Vue or React. However, I am interested ...

Designing an interactive region using HTML, CSS, and JavaScript

I recently created this code with some assistance: When I tried to format the code, it all ended up on one line and looked unreadable. To view the code properly, please visit this link: http://jsfiddle.net/QFF4x/ <div style="border:1px solid black;" ...

What is the best way to implement validation for a textfield to prevent submission if a negative value is entered?

I am working with a text field of type number and I have successfully set a minimum value of 0 to ensure that negative values are not accepted. However, I have encountered an issue where I am unable to delete the 0 once it is entered. Is there a way to fix ...

RouterContext Error: Invariant violation: Do not utilize <withRouter(App) /> in a context without a <Router> present

After wrapping my app with BrowserRouter and trying to export it as withRouter(App), I encountered the following error in the browser: 16 | return ( 17 | <RouterContext.Consumer> 18 | {context => { > 19 | invariant( | ^ ...

Looking to create a web service using XML?

What is the purpose of an XML Webservice? This type of webservice takes in an XML request and then responds with an XML response. I'm feeling uncertain about how to properly handle the requests. Should I extract the XML request from the page input pa ...

Automatically log users out of Django and update the backend after a period of inactivity without requiring any additional requests

In my Django project, I am working on a simple multiplayer system where I need to update the isCurrentlyActive value in a user-related model automatically and then log them out. I tried using middleware following a solution from this post, which works well ...

Leveraging data generated by a CasperJS script within an AngularJS application

After using yeoman.io to create an angular.js single page application, I found myself with app.js managing routes, mycontroller.js scripts, and an index.html file filled with "bower_components" references for libraries installed through the command line us ...

The V-model seems to be failing to bind to the DOM element

I'm encountering an issue with the code I've written. The v-model is not binding the data in the DOM, even though the axios I'm using is returning values. Here is the code snippet: <template> <v-container fluid> <v-layo ...