This
article will show you how you can validate a radio button in asp.net mvc
application using jquery. This article you can use in mvc3,mvc4,mvc5,mvc6 applications.
Some of my previous articles are as follows: Css Class Change of Button On Radiobutton Selection In Asp.Net Using jQuery, Stylish RadioButton, DropdownList, ListBox and TextBox Control In Asp.Net Using Css, Get RadioButton Value Using jQuery In Asp.Net, Disable And Enable Button Using jQuery In Asp.Net.
So for this article first we will create a new mvc application and add the controller in project.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication8
{
public class ValidationController : Controller
{
//
// GET: /Validation/
public ActionResult
Index()
{
return View();
}
}
}
|
Now create
the view of controller action and add the below mention jquery library reference.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
|
After this
we will add the below code for radiobutton control in mvc.
Radio Button:
@Html.RadioButton("Accept", false, new { @Id = "chkAccept" })
<input type="button" value="Click" id="btnValidation"
/>
|
Please
check the highlighted part of the code. In this I have added a button control
also. This button control I used for click.
Now check
the below jquery code.
$(document).ready(function () {
$("#btnValidation").click(function () {
var status = $("#chkAccept").prop("checked");
if (status == false) {
alert("Please click
radiobutton");
} else {
alert("You have selected
radiobutton.");
}
})
});
|
In above
code I have assigned the click event of the button control. In click event of
the button I have checked the status of the radiobutton weather it is checked
or not. Now check the complete code of the view page.
@{
ViewBag.Title
= "Validation Of RadioButton Using
jQuery In MVC6";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btnValidation").click(function () {
var status = $("#chkAccept").prop("checked");
if (status == false) {
alert("Please click
radiobutton");
} else {
alert("You have selected
radiobutton.");
}
})
});
</script>
Radio Button:
@Html.RadioButton("Accept", false, new { @Id = "chkAccept" })
<input type="button" value="Click" id="btnValidation"
/>
|
Now we have
done. Run the application to check the output.
0 comments:
Please let me know your view