Thursday, 19 May 2016

How to access asp.net mvc model fields values in jquery code.

You can access mvc model values in jquery by using Newtonsoft json serializer. It serialize your model object. And then you have to stringify that object by using JSON.stringify method of javascript and store that values in a vriable. After that you have to parses that stored value in a new variable by using JSON.parse method.

 Following are the javascript code how to access model fields value in javascript or in jquery.

 Model classes:-

namespace Demo.Models
{
    public class DropListModel
    {
    public int? Id { get; set; }
        public string Title { get; set; }
    }


    public class TestViewModel
    {
  
    private List<DropListModel> _DayList;
        public IEnumerable<SelectListItem> DayList
        {
            get
            {
                _DayList = new List<DropListModel>();
                _DayList.Add(new DropListModel() { Id = 0, Title = Resources.Select });
                for (int i = 1; i <= 31; i++)
                {
                    _DayList.Add(new DropListModel() { Id = i, Title = i.ToString() });
                }
                return new SelectList(_DayList, "Id", "Title");
            }
        }

    }

}


Controller Code here:-

public ActionResult AccessModelFiledValue(long id)
{
    TestViewModel oModel = new TestViewModel();
    return View(oModel);
}

AccessModelFiledValue.cshtml page code:-


@model Demo.Models.TestViewModel
@{
    ViewBag.Title = "Test";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
          
        </div>
</div>

//Javascript code here:-
<script type="text/javascript">

var serializedObject = JSON.stringify(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model.DayList)));

        var yourJsonData = JSON.parse(serializedObject );


</script>

No comments:

Post a Comment