Reputation: 95
I have a code where I used checkbox in order for the user to choose his preferences.
Here is the code in my controller.
[HttpPost]
public ActionResult Selected_Softwares(string[] type){
var results = db.Softwares_Reports_vw.Where(s => type.Contains(s.software_name)).OrderBy(s=>s.software_name);
//here i tried to pass the parameter to viewbag
ViewBag.type = type;
return PartialView(results);
}
In my view:
<span style="float:right"> <input type="button" style="border: 2px groove #FBF5EF; background-color:ActiveCaption;"
class="my-button" value="Export Data To Excel" name="back"
onclick="@("location.href='" + Url.Action("toExcel_Results2", "Softwares", new { softwares = ViewBag.type }) + "'")" /> </span>
And in my controller for the excel reports:
public ActionResult toExcel_Results2(string[] softwares)
{
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
return View(db.Softwares_Reports_vw.Where(s => softwares.Contains(s.software_name)).OrderBy(s=>s.software_name);
}
But the parameter here had no value. Why? Any help is greatly appreciated.
Upvotes: 1
Views: 3244
Reputation: 1523
If you look at the HTML (in the browser F12 tools) for the button labeled "Export Data To Excel" in your Softwares\Selected_Softwares view, you'll see something like this (look at the onclick event):
<input type="button" style="border: 2px groove #FBF5EF;
background-color:ActiveCaption;" class="my-button"
value="Export Data To Excel" name="back"
onclick="location.href='/Softwares/toExcel_Results2?softwares=System.String[]'">
Notice that the object that you put into your ViewBag (a string[]) simply is getting serialized in the HTML as literally "System.String[]". This is because all ASP.NET MVC does is call ToString() on that object. When you call ToString() on a string[], you get the string "System.String[]".
Here's what I would recommend... you seem to be wanting to send some data to your "toExcel_Results2" action. This usually indicates that you want a POST rather than a GET. Here's a fairly simple solution. Just change your Selected_Softwares view to include this:
@using (Html.BeginForm("toExcel_Results2", "Softwares", FormMethod.Post, new { id = "MyForm" }))
{
<span>
<input type="button" style="border: 2px groove #FBF5EF; background-color:ActiveCaption;"
class="my-button" value="Export Data To Excel" name="back"
onclick="document.getElementById('MyForm').submit();" />
@for (int i = 0; i < ViewBag.type.Length; i++)
{
@Html.Hidden("softwares[" + i.ToString() + "]", (string)ViewBag.type[i]);
}
</span>
}
With this, you'll find that your "toExcel_Results2" action is able to receive the full array of strings.
Upvotes: 3