Saturday 14 October 2017

MVC - jSon, JavaScript, jQuery - How to creat radiobuttons programmatically, load them with data and get selected ID and Name


Watch this example on YouTube:


Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_RadioButton.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public JsonResult GetValues()
        {
            List<User> u = new List<User>();
            u.Add(new User(111, "ANNA"));
            u.Add(new User(222, "BOB"));
            u.Add(new User(333, "JOHN"));
            u.Add(new User(444, "IRA"));
            return Json(u.Select(x => new
            {
                ID = x.ID,
                NAME = x.Name
            }));

        }
    }

    public class User
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public User(int id, string name)
        {
            ID = id;
            Name = name;
        }
    }
}

View:

@{
    ViewBag.Title = "Home Page";
}

<div id="test"></div>
<input type="submit" value="Get Selected Values" name="btn" id="btnRadio" />

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            var entries = {};
            entries.url = '@Url.Action("GetValues", "Home")';
            entries.type = "POST";
            entries.dataType = "json";
            entries.contentType = "application/json";
            entries.success = function (r) {
                $('#test').empty();
                for (var i = 0; i < r.length; i++) {
                    var label = $("<label for'" + r[i].ID + "'id='RadioButton'>" + r[i].NAME + "</label>");
                    label.appendTo('#test');
                    var radioButton = $("<input type='radio' class='SomeClass' id='"+ r[i].NAME + "' name='SomeName' value='" + r[i].ID + "'/>");
                    radioButton.appendTo('#test');
                }
            };
            entries.error = function (){alert("Error retrieving values")};
            $.ajax(entries);

            $("#btnRadio").click(function(e){
                var ID = $("input[name='SomeName']:checked").val();
                var Name = $("input[name='SomeName']:checked").attr('id');
                alert("Checked ID: " + ID + " checked name: " + Name);
            });
        });
    </script>
    }



No comments:

Post a Comment