2012-01-21 30 views
0

我實現了兩個動作:如何檢索方法POST URL參數[ASP.NET MVC]

它呈現URL中與消費者ID地址查看第一個動作:

這是URL http://localhost:90/Consumer/Address?id=18755

[HttpGet] 
public ActionResult Address(int id) 
{ 
return View(); 
} 

第二個動作是職位地址形式:

[HttpPost] 
public ActionResult Address(FormCollection value) 
{ 
    int id = Convert.ToInt32(Request["id"]); 
    // Some code ... 
    return View(); 
} 

當我發動保存操作時,我發現ID爲空,我想從Get操作中檢索conusmer ID?

回答

0

我想從獲取動作檢索conusmer ID?

您無法從GET操作中檢索它,因爲您現在正在執行POST操作。所以如果你想要檢索它,你將不得不發佈這個參數。

因此,例如,如果我們假設您的GET操作呈現了一個包含<form>的視圖,該視圖將用於POST,那麼您可以在此窗體中包含該ID作爲隱藏字段。當表單提交它通過這種方式將被髮送到第二個動作:

@using (Html.BeginForm()) 
{ 
    @Html.Hidden("id", Request["id"]) 

    ... some other input fields 
    <button type="submit">OK</button> 
} 

此外,在您的POST操作,而不是做一些手工類型轉換隻使用默認模式粘結劑爲你做的。定義視圖模型:

public class MyViewModel 
{ 
    public int Id { get; set; } 

    ... some other properties 
} 

,然後讓POST操作持這種觀點模型作爲操作參數:

[HttpPost] 
public ActionResult Address(MyViewModel model) 
{ 
    int id = model.Id; 
    // Some code ... 

    return View(); 
}