In the view I have a lot of RadioButtons
and the id is the unique for each one. when user choose one of those in controller I would like to take the ID
and VALUE
how i can do that.... i try with formCollection
but in here i just can take value...
@Html.RadioButton("BookType", "1", new { id = "100" })
<br>
Above code generates Below code
<br/>
< input id="100" name="BookType" type="radio" value="1" >
and the question is how can I take the ID and VALUE by 'POST'
Action in the control.
You can write code in Post Action as follow:
var radbtn = Request.From["100"];
You don't, that's not how form controls work.
When you submit a form, the name
and value
are submitted, except for scenarios like checkbox
and radio
inputs.
Only when a checkbox
is checked
, or a radio input
is checked
are the name/value
posted.
You need to re-think what you're trying to achieve. If you can give some more information what you want to achieve I'm sure I or anyone else can help further.
I suggest you to use view model. Please see this example bellow:
namespace MvcApplication1.Controllers {
public class TheOption {
public string Id { get; set; }
public string Value { get; set; }
public bool? Checked { get; set; }
}
public class FooController : Controller {
//
// GET: /Foo/
public ActionResult Index() {
var options = new List<TheOption> {
new TheOption {Id = "One", Value = "The One"},
new TheOption {Id = "Two", Value = "The Two"},
new TheOption {Id = "Hundred", Value = "The Hundred"},
};
return View(options);
}
[HttpPost]
public ActionResult Index(List<TheOption> options) {
return View(options);
}
}
}
Now you need to create editor template for TheOption
model. It's simply by create folder named EditorTemplates under ~\Views\Shared\ folder. Add new view as the editor template. Name this editor template to match with the model name (TheOption
).
Here's the content of ~\Views\Shared\EditorTemplates\TheOption.cshtml:
@model MvcApplication1.Controllers.TheOption
<div>
@Html.RadioButtonFor(m => m.Checked, true, new { id = Model.Id + "_selected" })
@Html.RadioButtonFor(m => m.Checked, false, new { id = Model.Id }) @Model.Value
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.Value)
</div>
Now go to your main view (Index.cshtml) and simply put this code:
@model System.Collections.Generic.List<MvcApplication1.Controllers.TheOption>
@using (Html.BeginForm()) {
@Html.EditorFor(m=>m)
<button type="submit">Save</button>
}
Done! Hope this helps :)