I have a view that has two buttons(“First” and “Second”) and one hidden field. When user clicks on “First” button, hidden field will be set as the value of “data-myAttribute” attribute in the first button. When user clicks on “Second” button, hidden field will be set as the value of “data-myAttribute” attribute in the second button. Once the hidden field is set, the form need to be submitted. This much is working fine with the following code. Further, I need to be able to see the value of the hidden field in the controller. How do we get the value in controller?
namespace MyHiddenFieldTest.Controllers
{
public class ElementController : Controller
{
public class MyViewModel
{
public string ControlName { get; set; }
}
// GET:
public ActionResult MyElement()
{
MyViewModel myViewModel = new MyViewModel();
return View(myViewModel);
}
// POST:
[HttpPost]
public ActionResult MyElement(MyViewModel theViewModel)
{
string selectedControl = theViewModel.ControlName;
return View(theViewModel);
}
}
}
VIEW
@model MyHiddenFieldTest.Controllers.ElementController.MyViewModel
@{
ViewBag.Title = "MyElement";
}
<h2>MyElement</h2>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function ()
{
$('#mainDiv input[type="button"]').on('click', function ()
{
$('#from').val($(this).attr('data-myAttribute'));
alert($('#from').val());
$(this).closest('form').submit();
});
});
</script>
@using (Html.BeginForm())
{
<div id="mainDiv">
<input type="button" value="First" data-myAttribute="theFirst" />
<input type="button" value="Second" data-myAttribute="theSecond" />
<input type="hidden" id="from" value="1" />
<input type="hidden" id="to" value="2" />
</div>
}
READING
- Passing JSON data from controller action to a razor view