2013-08-05 79 views
0

我在C#中使用ASP.NET MVC 4,我試圖將一個ActionResult方法的參數變成另一個方法中使用的變量。所以我有這樣的例子:看似愚蠢的查詢參數

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

我需要INT SER以某種方式成爲「全球性」,並將其值可用此方法:

public ActionResult AddServiceToInvoice(int id) 
    { 

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

正如你可以在我的return語句只是看到上面,我得到一個錯誤,因爲我沒有將變量「ser」傳遞給Index,但我需要它是與調用動作時傳遞給Index的值相同的值。任何人都可以協助

+0

怎樣的方法關聯? – Sayse

+0

您可以查看任何示例如何在視圖中生成網址動作...如果示例不可用 - 請在您的問題中發佈視圖代碼。 –

回答

0

您需要創建與ID鏈接:

如果你正在做一個GET請求,將是這樣的:如果你想要做一個帖子你

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

否則需要創建一個表單:當你建立你的鏈接到該方法

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

,你需要確保你通過你的變量ser的方法與任何一起行吟詩人r參數(它不清楚AddServiceToInvoice方法中的ID實際上是否爲ser參數。這是假設它不是)

操作鏈接在搜索

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

AddServiceToInvoice操作方法

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