I am fairly new to MVC. I have a simple problem. I have 3 radio buttons on my开发者_开发技巧 mvc asp.net page. I would like to call an action in my controller when I check one of the radio buttons on the page. How do I do a postback in mvc?
If you had radio buttons like:
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
You could add script (assuming you can use jQuery) on the page like:
<script type="text/javascript">
$(function () {
$(':radio[name="sex"]').change(function () {
$.ajax({
url: 'sex',
type: 'POST',
data: { sex: $(':radio[name="sex"]:checked').val() },
success: function (xhr_data) {
alert(xhr_data.someValue);
}
});
});
});
</script>
Assuming you have an action method in the same controller as the one that generated your view:
public class YourController : Controller
{
public ActionResult sex(string sex)
{
// do something awesome
return Json(new { someValue = "testing!" });
}
}
The answer above only worked for me when I did
data: { sex: $('radio[name="sex"]:checked').val() },
That is, when I added ':checked' to the selector.
精彩评论