To pass values from the client to the server, you have two options: make a GET request and pass the value in the query-string; or use a
<form>
to make a POST request.
@foreach (DataColumn col in Model.ModelPageDataRow.Columns)
{
using (Html.BeginForm("ActionName"))
{
@Html.Hidden("PassedId", row[col.ColumnName]);
<button type="submit">@row[col.ColumnName]</button>
}
}
You can use CSS to style the button to look like a link if required.
NB: Forms cannot be nested. If you already have a form wrapping this code, you will have to use the query-string.
On the server side, rather than accessing the
Request.QueryString
or
Request.Form
collections, just use model binding to retrieve the value:
public ActionResult ActionName(string passedId)
{
Session["SomeId"] = passedId;
---Rest of the code
}
Edit: An alternative approach if you already have a form wrapping the code:
Make the buttons submit the parent form with a specific name and value:
@foreach (DataColumn col in Model.ModelPageDataRow.Columns)
{
<button type="submit" name="SendThisIdToTheOtherAction" value="@row[col.ColumnName]" formnovalidate>@row[col.ColumnName]</button>
}
Update the existing action to check whether one of the buttons has been clicked. If it has, store the value in
TempData
and redirect to the new action:
public ActionResult ActionThatYourFormPostsTo(string sendThisIdToTheOtherAction = null)
{
if (!string.IsNullOrEmpty(sendThisIdToTheOtherAction))
{
TempData["PassedId"] = sendThisIdToTheOtherAction;
return RedirectToAction("ActionName");
}
...
}
Update the new action to read the value from
TempData
:
public ActionResult ActionName()
{
string passedId = (TempData.TryGetValue("PassedId", out object id) ? Convert.ToString(id) : null;
...
}
NB: The
formnovalidate
attribute on the button should prevent the jQuery validation plugin from attempting to validate the form when one of these buttons is clicked. If you've written your own validation scripts, you will need to update them accordingly.