barnacle.m
barnacle.m

Reputation: 2200

Seemingly silly query about parameters

I am working in ASP.NET MVC 4 with C#, and i'm trying to turn the parameter of one ActionResult method into a variable for use in another method. So I have this for example:

    public ActionResult Index(int ser)
    {
        var invoice = InvoiceLogic.GetInvoice(this.HttpContext);

        // Set up our ViewModel
        var pageViewModel = new InvoicePageViewModel
        {
            Orders = (from orders in proent.Orders
                      where orders.Invoice == null
                            select orders).ToList(),
            Callouts = (from callouts in proent.Callouts
                        where callouts.Invoice == null
                            select callouts).ToList(),
            InvoiceId = ser,
            InvoiceViewModel = new InvoiceViewModel
        {
            InvoiceId = ser,
            InvoiceItems = invoice.GetInvoiceItems(),
            Clients = proent.Clients.ToList(),
            InvoiceTotal = invoice.GetTotal()
        }
    };
        // Return the view
        return View(pageViewModel);
    }

I need that int ser to somehow become "global" and its value become available to this method:

    public ActionResult AddServiceToInvoice(int id)
    {

        return Redirect("/Invoice/Index/");
    }

As you can see in my return statement just above, I get an error as I am not passing the variable "ser" back to Index, but I need it to be the same value that was passed to Index when the action was called. Can anyone assist?

Upvotes: 0

Views: 93

Answers (2)

Tommy
Tommy

Reputation: 39807

When you construct your link to that method, you need to ensure you are passing your variable ser to the method along with any other parameters that it needs (it is unclear if the id in the AddServiceToInvoice method is actually the ser parameter or not. This assumes it is not)

Action Link In View

@Html.ActionLink("Add Service", "Invoice", "AddServiceToInvoice", new {id = IdVariable, ser = Model.InvoiceId})

AddServiceToInvoice Action Method

public ActionResult AddServiceToInvoice(int id, int ser)
    {
        //Use the redirect to action helper and pass the ser variable back
        return RedirectToAction("Index", "Invoice", new{ser = ser});
    }

Upvotes: 1

Kenneth
Kenneth

Reputation: 28737

You need to create a link with that ID:

if you're doing a get-request that would be something like this:

@Html.ActionLink("Add service to invoice", "Controller", "AddServiceToInvoice", 
new {id = Model.InvoiceViewModel.InvoiceId})

Otherwise if you want to do a post you need to create a form:

@using Html.BeginForm(action, controller, FormMethod.Post)
{
    <input type="hidden" value="@Model.InvoiceViewModel.InvoiceId" />
    <input type="submit" value="Add service to invoice" />
}

Upvotes: 0

Related Questions