未加星标

Populate MVC Listbox using jQuery getJSON and JSONResult

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Create a new application with Basic or MVC template name it as MVCListBoxExample .

Create controller with name HomeController . For detail steps on creating MVC application and Controller see Getting started with ASP.NET MVC

Open HomeController.cs file from Controllers folder, you will see Index Action Method. Right click on Index action method and select Add View . New dialog box opens leave the View Name and other values as it is and click OK. It adds a new view with Index.cshtml name under Views -> Home folder.

In Index.cshtml view add HTML ListBox helper to display category values. Add below html code to Index.cshtml file

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div style="margin:25px;">
<div>
<h2>Fill MVC ListBox using jQuery getJSON and JSONResult</h2>
</div>
<div>
<b>Categories</b>
</div>
<div>
@Html.ListBox("Categories", new SelectList(new[] { "" }),
new { @class = "list-group", @style = "width: 150px; height:150px; margin:15px;" })
</div>
</div>

Run your application you will see Index view with empty ListBox.

Now open HomeController and add Action method which returns JSONResult. Add below code to HomeController.cs file which can be called by jQuery.getJSON.

public JsonResult GetCategories()
{
Dictionary<string, string> lstCategories = new Dictionary<string, string>();
lstCategories.Add("1", "Beverages");
lstCategories.Add("2", "Condiments");
lstCategories.Add("3", "Confections");
lstCategories.Add("4", "Dairy Products");
lstCategories.Add("5", "Grains/Cereals");
lstCategories.Add("6", "Meat/Poultry");
lstCategories.Add("7", "Produce");
lstCategories.Add("8", "Seafood");
return Json(lstCategories, JsonRequestBehavior.AllowGet);
}

Now add a jQuery.getJSON function to call GetCategories controller action method and get Json result. Remember jQuery.getJSON will work only with HTTP Get request. If you have HTTP Post action methods then you will have to usejQuery Ajax Call.

Add below code to Index.cshtml file

<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON('home/GetCategories/', function (data) {
//clear the current content of the select
$('#Categories').empty();
//iterate over the data and append a select option
$.each(data, function (key, val) {
$('#Categories').append('<option id="' + key + '">' + val + '></option>');
})
});
});
</script> Populate Listbox with Model values

In previous step you added static values to Listbox. In this step you will add Listbox options from MVC model values. For simplicity I have added some static values from Northwind database to model. You can add it using Entity framework or ADO.NET from your database.

Add new model under Models folder with name Category . Add below properties to it.

namespace MVCListBoxExample.Models
{
public class Category
{
public string CategoryID { get; set; }
public string CategoryName { get; set; }
}
}

Open HomeController.cs file and add below code which add Category values and return JSON result.

public JsonResult GetCategoriesWithModel()
{
List<Category> lstCateogories = new List<Category>();
lstCateogories.Add(new Category(){CategoryID="1", CategoryName="Beverages" });
lstCateogories.Add(new Category(){CategoryID="2", CategoryName="Condiments" });
lstCateogories.Add(new Category(){CategoryID="3", CategoryName="Confections" });
lstCateogories.Add(new Category(){CategoryID="4", CategoryName="Dairy Products" });
lstCateogories.Add(new Category(){CategoryID="5", CategoryName="Grains/Cereals" });
lstCateogories.Add(new Category(){CategoryID="6", CategoryName="Meat/Poultry" });
lstCateogories.Add(new Category(){CategoryID="7", CategoryName="Produce" });
lstCateogories.Add(new Category(){CategoryID="8", CategoryName="Seafood" });
return Json(lstCateogories, JsonRequestBehavior.AllowGet);
}

Now add jQuery code to call GetCategoriesWithModel

$(document).ready(function () {
$.getJSON('home/GetCategoriesWithModel/', function (data) {
//clear the current content of the select
$('#Categories').empty();
//iterate over the data and append a select option
$.each(data, function (i, item) {
$('#Categories').append('<option value="' + item.CategoryID + '">' + item.CategoryName + '></option>');
})
});
}); Populate Listbox from JSON file

You can also read data from text file which is in JSON format. Add a text file in root directory with name Categories.txt . You cannot use JSON extension as it is not accessible to browser through HTTP request.

Add below JSON to Categories.txt.

[
{
"CategoryID" : 1,
"CategoryName" : "Beverage"
},
{
"CategoryID" : 2,
"CategoryName" : "Condiment"
},
{
"CategoryID" : 3,
"CategoryName" : "Confection"
},
{
"CategoryID" : 4,
"CategoryName" : "Beverage"
},
{
"CategoryID" : 5,
"CategoryName" : "Dairy"
},
{
"CategoryID" : 6,
"CategoryName" : "Grains"
},
{
"CategoryID" : 7,
"CategoryName" : "Seafood"
}
]

Add below jQuery code in index.cshtml file which reads JSON formatted data from text file.

$(document).ready(function () {
$.getJSON('Categories.txt', function (data) {
//clear the current content of the select
$('#Categories').empty();
//iterate over the data and append a select option
$.each(data, function (i, item) {
$('#Categories').append('<option value="' + item.CategoryID + '">' + item.CategoryName + '></option>');
})
});
});

It generates below output.


Populate MVC Listbox using jQuery getJSON and JSONResult

Download source code.

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: jQueryASP.NET MVCAjaxHTMLJavaJavaScript
分页:12
转载请注明
本文标题:Populate MVC Listbox using jQuery getJSON and JSONResult
本站链接:http://www.codesec.net/view/484042.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(25)