EDIT: Read the bottom of my question to see what I actually did. I accepted a different answer, though because my solution requires AngularJS.
I'm using C# 4.0 and MVC 3/Razor. I'd prefer to leverage existing functionality of the framework rather than make my own helper classes. Here's what I'm doing, simplified:
Here's my model:
MyModel.cs
public class MyModel
{
public string Name { get; set; }
public int ID { get; set; }
}
And my view, so far:
Index.cshtml
@model IEnumerable<MyModel>
Please select a Model.
<select name="id">
@foreach (var m in Model)
{
<option value="@(m.ID)">@(m.ID) - @(m.Name)</option>
}
</select>
And my controller:
MyController.cs
public class MyController : Controller
{
public ActionResult Index() { /* ... */ }
public ActionResult Display(int id) { /* ... */ }
public ActionResult Delete(int id) { /* ... */ }
public ActionResult Edit(int id) { /* ... */ }
}
In my view, I want to have three submit buttons, each linking to a different controller/action, one for Edit, Delete and Display. However I would like the ID that the user has selected to be passed (via GET). How do I do this?
I know I could make a new controller action whose sole purpose is to determine which of the three to choose, based on the value
of a submit
type input
element, but that approach seems ugly to me; I'd like to bypass that step. Ideally I'd want something like:
@using (Html.BeginForm("", "", FormMethod.Get))
{
<select name="id">
@foreach (var m in Model)
{
<option value="@(m.ID)">@(m.ID) - @(m.Name)</option>
}
</select>
@Html.SubmitButton("Edit", "My")
@Html.SubmitButton("Delete", "My")
@Html.SubmitButton("Display", "My")
}
But I can't find any method signatures in Html
that seem to do something like that.
EDIT:
Here's what I ended up going with. It uses a JavaScript library called AngularJS, but requires no additional JavaScript plumbing. It just works.
@model IEnumerable<MyModel>
<html>
<head>
<script type="text/javascript" src="../../Scripts/angular.js"></script>
</head>
<body ng-app>
<select ng-model="ID">
@foreach (var m in Model)
{
<option value="@(m.ID)">@(m.ID) - @(m.Name)</option>
}
</select>
@{
var forms = new[]
{
new { ActionName = "Display", ControllerName = "My" },
new { ActionName = "Edit", ControllerName = "My" },
new { ActionName = "Delete", ControllerName = "My" }
};
foreach (var form in forms)
{
using (Html.BeginForm(form.ActionName, form.ControllerName, FormMethod.Get))
{
<input type="submit" value="@(form.ActionName)" ng-disabled="ID == null"/>
<input type="hidden" name="id" value="{{ID}}"/>
}
}
}
</body>
</html>