2012-09-12 49 views
1

我在我的視圖(複選框)上有一個字段,它具有來自模型的id值。我需要將用戶在窗體上檢查的那些id的列表返回給控制器操作。返回不是模型中的數據到mvc控制器

我試過的每一件事都不起作用。我有視圖編碼返回到控制器,但我還沒有想出如何返回所需的值。

這是在視圖中的複選框的片段......

<td @trFormat > 
    <input id="ExportCheck" type="checkbox" value = "@item.PernrId" onclick="saveid(value);"/> 
</td> 

目前的onclick事件開火應存儲ID值視圖一個javascript ...

<script type="text/javascript"> 
    var keys = null; 
    function saveid(id) { 
     keys += id; 
    } 
</script> 

我一直在嘗試使用動作調用來回到控制器。目前,是因爲我無法弄清楚如何加載它被送回沒有路由對象...

<input type="submit" value="Export to Excel" onclick="location.href='@Url.Action("ExportExcel","CastIndex")'" /> 

我知道我可能做很多事情不對的代碼。我現在正在開發我的第一個MVC應用程序。任何幫助,將不勝感激。 最終的結果是我需要控制器中的ID來檢索選定的ID並將它們發送到excel導出。

+1

你不應該使用一個模型?然後你可以這樣做http://stackoverflow.com/questions/9973977/asp-net-mvc-3-retrieve-checkbox-list-values – user1477388

回答

0

你可以使用強類型的模型,看起來像:

public class Item 
{ 
    public int Id { get; set; } 
    public string Name { get; set;} 

    //Other properties... 

    public bool Export {get; set;} //for tracking checked/unchecked 
} 

在你的控制器的GET行動,建立一個列表,並傳遞到一個強類型的視圖。

[HttpGet] 
public ActionResult MyAction() 
{ 
    var model = new List<Item>(); 

    //ToDo: Get your items and add them to the list... Possibly with model.add(item) 

    return View(model); 
} 

在視圖中,您可以使用HTML助手「CheckBoxFor」爲列表中的每個項目添加複選框項目。

@using (Html.BeginForm()) 
{ 

//other form elements here 

@Html.CheckBoxFor(model=>model.Export) //this add the check boxes for each item in the model 

<input type="submit" value="Submit" /> 

} 

你的控制器的POST操作會消耗清單,並找出那些與出口==真:

[HttpPost] 
public ActionResult MyAction (List<Item> items) 
{ 
    foreach(Item i in Items) 
    { 
    if(i.Export) 
    { 
     //do your thing... 
    } 
    } 

    //Return or redirect - possibly to success action screen, or Index action. 
} 
相關問題