Receive parameters in action controller JSON
I’ve implemented a standard MVC Controller model with EF in ASP.NET MVC 5 and incorporated a customized action.
To implement my proposal, I suggest invoking this operation through an AJAX request to populate a select2 dropdown labeled as dynamically populate .
... public JsonResult getWarrehouses(string name) { var warrehouses = from c in db.warrehouses where c.nom_wrh.Contains(name) orderby c.nom_wrh select new { c.cod_wrh, c.nom_wrh} ; return Json(warrehouses.ToList(), JsonRequestBehavior.AllowGet); } ...
I am facing an issue with passing parameters to an action, where the provided parameter is always null. Despite trying to pass GET parameters through the URL, the parameter remains unreceived. I am unsure how to declare the action to receive these parameters and would appreciate alternative solutions if my current approach is incorrect.
Solution 1:
The issue could arise during the call. For instance, if your parameter on the Action is referred to as “name”.
$.ajax({ type: "POST", url: @Url.Action("getWarrehouses"), data: { name: VALUE_TO_PASS }, success: function (data) { // Manipulate (data) }
Solution 2:
To utilize browser extensions, such as Postman, it is necessary. Postman can be found at https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en.
They assist in sending requests to obtain warehouses using the get/post method along with the specified parameters.
Passing Json data to MVC controller
Apologies for any errors in formatting or spelling as I am writing this post hastily. 🙂
I am sending Json data as an input parameter to the action method method of a basic controller (MVC controller. Please refer to the following code sample.
JS CODE:
A JSON object has been declared with a boolean value assigned to the key ” isinit ” and a nested object named “SearchParam” with three properties: “Type”, “Name”, and “sort” with empty values assigned to the first two and unspecified value assigned to the last one.
Nx$(document).ready(function () { Nx$.ajax({ async: true, contentType: "application/json; charset=utf-8", type: "POST", url: "Home/Data", dataType: "json", data: JSON.stringify(json), success: function (msg) { alert('success'); }, error: function (jqxhr, textStatus, error) { alert('fail'); } });
Method of operation:
Function GetData(ByVal IsInit As Boolean, ByVal SearchParam As Newtonsoft.Json.Linq.JObject) As ActionResult Return Nothing End Function
The action mentioned earlier does not invoke, however, implementing the code below will make the call. Nonetheless, it is important to note that the SearchParam object is of type [object], and thus, it cannot accept any value.
Public Function GetData(ByVal IsInit As Boolean, ByVal SearchParam As Object) As Object Return Nothing End Function
In my opinion, dealing with intricate JSON objects in POST request cannot be accomplished by pass multiple parameter functionality.
Is it possible to pass json data to the action method of MVC controller without making any significant changes to the initial method signature, in order to convert the SearchParam Json data to a JObject by itself?
Few Observation :
-
If I were to convert the aforementioned action method into an API in the API Controller, it would function properly. However, it is important to adhere to the specified method signature. It should be noted that this approach is not effective for the MVC controller, although it is unclear why. Despite this, utilizing the API controller is not feasible for me at this time.
Function GetData(ByVal req As Newtonsoft.Json.Linq.JObject) As ActionResult Return Nothing End Function
Thanks !!
Solution 1:
It is not advisable to employ JOBject for this purpose. It is more efficient and strongly suggested to generate and employ a Model class instead. By doing so, MVC Web API will automatically bind the incoming JSON to a Model object without any additional cost.
Example:
Public Class MyData Public Property IsInit As Boolean Public Property Type As String Public Property Name As String Public Property Sort As String End Class
Please note that all the code has been combined into a single class. In case you prefer to keep
IsInit
distinct from the rest, you may divide it into a separate class.
Public Class Param Public Property Type As String Public Property Name As String Public Property Sort As String End Class Public Class MyData Public Property IsInit As Boolean Public Property SearchParam as Param End Class
Modify your Action Method as follows:
Function GetData(
ByVal data As MyData) As ActionResult … End Function
To ensure the proper functioning of your call, it is recommended to include
data: json
and refrain from calling
JSON.stringify()
.
Solution 2:
Peter, thank you for providing me with guidance. I utilized the code snippet below to encapsulate JSON data within Dictionary Object . While I appreciate your suggestion to avoid using JObject and instead use a Model object, I am required to use a dictionary object due to the dynamic nature of the JSON received from the endpoint.
Public Class MyData Public Property IsInit As Boolean Public Property SearchParam As Dictionary(Of Object, Object) End Class
Thanks a lot !!
The title sums it up – I need to send JSON data from a client to asp.net MVC using JQuery. I’m curious if it can receive any type of JSON data without requiring a specific type or model representation. Essentially, I’m looking for a dynamic type that doesn’t need to be parsed.
When I declared the passing argument as an Object type in the usual way, it resulted in nulls as I had anticipated.
Essentially, my aim is to perform a form of “JSON reflection” upon receiving it, allowing me to access its attributes using a designated pattern such as foreach loop and so on.
I appreciate your assistance beforehand. Your help is highly valued.
Solution:
An
IDictionary
can be utilized as an argument for action by employing a custom model binder to convert a
JSON request
into it.
public class DictionaryModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { return null; } controllerContext.HttpContext.Request.InputStream.Position = 0; using (var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream)) { var json = reader.ReadToEnd(); if (string.IsNullOrEmpty(json)) { return null; } return new JavaScriptSerializer().DeserializeObject(json); } } }
The registration will occur under the MSDT code
Application_Start
.
ModelBinders.Binders.Add(typeof(IDictionary
), new DictionaryModelBinder());
You may create a controller action in the following manner:
[HttpPost] public ActionResult Foo(IDictionary
model) { return Json(model); }
to which you can throw anything:
var model = { foo: { bar: [ 1, 2, 3 ], baz: 'some baz value' } }; $.ajax({ url: '@Url.Action("foo")', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(model), success: function (result) { // TODO: process the results from the server } });
jQuery $.get() Method
The
$.get()
method requests data from the server with an HTTP GET request.
Syntax:
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the
$.get()
method to retrieve data from a file on
the server:
Example
$.get(“demo_test.asp”, function(data, status){
alert(“Data: ” + data + “\nStatus: ” + status);
});
});
The first parameter of
$.get()
is the URL we wish to request (“demo_test.asp”).
The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like (“demo_test.asp”):
response.write(“This is some text from an external ASP file.”)
%>
jQuery.getJSON( url [, data ] [, success ] )Returns: jqXHR
Description: Load JSON-encoded data from the server using a GET HTTP request.
-
version added: 1.0jQuery.getJSON( url [, data ] [, success ] )
- urlType: StringA string containing the URL to which the request is sent.
- dataType: PlainObject or StringA plain object or string that is sent to the server with the request.
- successType: Function( PlainObject data, String textStatus, jqXHR jqXHR )A callback function that is executed if the request succeeds.
This is a shorthand Ajax function, which is equivalent to:
Data that is sent to the server is appended to the URL as a query string. If the value of the
data
parameter is a plain object, it is converted to a string and url-encoded before it is appended to the URL.
Most implementations will specify a success handler:
10 11 |
This example, of course, relies on the structure of the JSON file:
Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.
The
success
callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the
$.parseJSON()
method. It is also passed the text status of the response.
As of jQuery 1.5, the
success
callback function receives a “jqXHR” object (in jQuery 1.4, it received the
XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the
jqXHR
and
textStatus
parameters passed to the success callback are undefined.
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript’s object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see https://json.org/.
JSONP
If the URL includes the string “callback=?” (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the
jsonp
data type in
$.ajax()
for more details.
The jqXHR Object
As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the
XMLHTTPRequest
object. This jQuery XHR object, or “jqXHR,” returned by
$.getJSON()
implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The
jqXHR.done()
(for success),
jqXHR.fail()
(for error), and
jqXHR.always()
(for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the
$.ajax()
documentation.
The Promise interface in jQuery 1.5 also allows jQuery’s Ajax methods, including
$.getJSON()
, to chain multiple
.done()
,
.always()
, and
.fail()
callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
10 11 12 13 14 15 16 17 18 19 20 21 |
Deprecation Notice
The
jqXHR.success()
,
jqXHR.error()
, and
jqXHR.complete()
callback methods are removed as of jQuery 3.0. You can use
jqXHR.done()
,
jqXHR.fail()
, and
jqXHR.always()
instead.
Additional Notes:
- Due to browser security restrictions, most “Ajax” requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
- Script and JSONP requests are not subject to the same origin policy restrictions.
HTTP Request: GETPOST
Two commonly used methods for a request-response between a client and server are: GET and POST.
- GET – Requests data from a specified resource
- POST – Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POST chapter.
jQuery.getJSON( url [, data ] [, success ] )Returns: jqXHR
Description: Load JSON-encoded data from the server using a GET HTTP request.
-
version added: 1.0jQuery.getJSON( url [, data ] [, success ] )
- urlType: StringA string containing the URL to which the request is sent.
- dataType: PlainObject or StringA plain object or string that is sent to the server with the request.
- successType: Function( PlainObject data, String textStatus, jqXHR jqXHR )A callback function that is executed if the request succeeds.
This is a shorthand Ajax function, which is equivalent to:
Data that is sent to the server is appended to the URL as a query string. If the value of the
data
parameter is a plain object, it is converted to a string and url-encoded before it is appended to the URL.
Most implementations will specify a success handler:
10 11 |
This example, of course, relies on the structure of the JSON file:
Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.
The
success
callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the
$.parseJSON()
method. It is also passed the text status of the response.
As of jQuery 1.5, the
success
callback function receives a “jqXHR” object (in jQuery 1.4, it received the
XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the
jqXHR
and
textStatus
parameters passed to the success callback are undefined.
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript’s object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see https://json.org/.
JSONP
If the URL includes the string “callback=?” (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the
jsonp
data type in
$.ajax()
for more details.
The jqXHR Object
As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the
XMLHTTPRequest
object. This jQuery XHR object, or “jqXHR,” returned by
$.getJSON()
implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The
jqXHR.done()
(for success),
jqXHR.fail()
(for error), and
jqXHR.always()
(for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the
$.ajax()
documentation.
The Promise interface in jQuery 1.5 also allows jQuery’s Ajax methods, including
$.getJSON()
, to chain multiple
.done()
,
.always()
, and
.fail()
callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
10 11 12 13 14 15 16 17 18 19 20 21 |
Deprecation Notice
The
jqXHR.success()
,
jqXHR.error()
, and
jqXHR.complete()
callback methods are removed as of jQuery 3.0. You can use
jqXHR.done()
,
jqXHR.fail()
, and
jqXHR.always()
instead.
Additional Notes:
- Due to browser security restrictions, most “Ajax” requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
- Script and JSONP requests are not subject to the same origin policy restrictions.
jQuery AJAX Reference
For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.
html
head
title
How to convert JSON data to a html
table using JavaScript/jQuery ?
title
script
src
script
head
body
style
"text-align:center;"
h1
style
"color:green;"
GeeksForGeeks
h1
id
"GFG_UP"
style
"font-size: 15px; font-weight: bold;"
button
onclick
"GFG_FUN()"
click here
button
br
><
br
table
id
"table"
align
"center"
border
"1px"
>
table
script
let el_up = document.getElementById("GFG_UP");
let list = [
"col_1": "val_11", "col_2": "val_12",
"col_3": "val_13"
},
"col_1": "val_21", "col_2": "val_22",
"col_3": "val_23"
},
"col_1": "val_31", "col_2": "val_32",
"col_3": "val_33"
];
el_up.innerHTML = "Click on the button to create the "
+ "table from the JSON data.<
br
><
br
>"
+ JSON.stringify(list[0]) + "<
br
>"
+ JSON.stringify(list[1]) + "<
br
>"
+ JSON.stringify(list[2]);
function GFG_FUN() {
let cols = [];
for (let i = 0; i <
list.length
; i++) {
for (let k in list[i]) {
if (cols.indexOf(k) === -1) {
// Push all keys to the array
cols.push(k);
// Create a table element
let
table
document
.createElement("table");
// Create table row tr element of a table
let
tr
table
.insertRow(-1);
for (let
; i < cols.length; i++) {
// Create the table header th element
let
theader
document
.createElement("th");
theader.innerHTML
cols
[i];
// Append columnName to the table row
tr.appendChild(theader);
// Adding the data to the table
for (let
; i < list.length; i++) {
// Create a new row
trow
table
.insertRow(-1);
for (let
; j < cols.length; j++) {
let
cell
trow
.insertCell(-1);
// Inserting the cell at particular place
cell.innerHTML
list
[i][cols[j]];
// Add the newly created table containing json data
let
el
document
.getElementById("table");
el.innerHTML
""
el.appendChild(table);
body
html
In this article I am going to show how to display data using jQuery, AJAX Call, JSON in ASP.NET MVC Application.
Open Visual Studio, then Add New Project.
Below is my Data Table in design mode from which I will show data.
Script of my Data Table,
- CREATE TABLE [dbo].[Emp_Information](
- [EMP_ID] [int] IDENTITY(1,1)NOTNULL,
- [Name] [varchar](50)NULL,
- [ProjectName] [varchar](50)NULL,
- [ManagerName] [varchar](50)NULL,
- [City] [varchar](50)NULL,
- [Joining_Date] [datetime] NULL,
- CONSTRAINT [PK_Emp_Information] PRIMARYKEYCLUSTERED
- [EMP_ID] ASC
- )WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,
- IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON [PRIMARY]
- )ON [PRIMARY]
- GO
- SETANSI_PADDINGOFF
- GO
Data in my Data Table:
Now add an ADO.NET Entity Data Model. So, right click on Project Solution Explorer,
Add
, then click
New Item
Select
ADO.NET Entity Data Model
Now Right Click on
Models
Folder, Add, then New Class. Here’s the screenshot,
Now add a new Controller, Right Click on Controller Folder and then Add New Controller,
Here in this controller do the following code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using ShowListData_jQuery_JSON_MVC.Models;
- namespace ShowListData_jQuery_JSON_MVC.Controllers
- public class EmployeeController: Controller
- public ActionResult Index()
- return View();
- public JsonResultGetAllEmployee()
- CompanyDBEntitiesobj = new CompanyDBEntities();
- var contacts = obj.Emp_Information.Select(x => new
- Id = x.EMP_ID,
- Name = x.Name,
- ProjectName = x.ProjectName,
- ManagerName = x.ManagerName,
- city = x.City
- }).ToList();
- return Json(contacts, JsonRequestBehavior.AllowGet);
- Now my View(Index.cshtml):
- @ {
- ViewBag.Title = ” Showing Data Using jQuery Ajax Call JSON in ASP.NET MVC”;
- } <
- h1 >
- Showing Data Using jQuery Ajax Call JSON in ASP.NET MVC <
- /h1> <
- div >
- tableid = “tblEmployee”
- class = “tblEmployee” >
- thead >
- img src = “~/Loading.gif”
- alt = “Loading”
- id = “imgLoading”
- class = “Load” / >
- /thead> <
- tbody > < /tbody> <
- /table> <
- /div> <
- script src = “~/Scripts/jquery-1.10.2.min.js” > < /script> <
- script type = “text/javascript” >
- $(document).ready(function()
- $(“#tblEmployeetbodytr”).remove();
- $.ajax
- ({
- type: ‘POST’,
- url: ‘@Url.Action(“GetAllEmployee”)’,
- dataType: ‘json’,
- data: {},
- success: function(data)
- $(“#imgLoading”).hide();
- var items = ”;
-
var rows = ”
” +
-
”
Employee ID Name Project Name Manager Name City ” +
- “”;
- $(‘#tblEmployeetbody’).append(rows);
- $.each(data, function(i, item)
-
var rows = ”
” +
-
”
” + item.Id + ” ” +
-
”
” + item.Name + ” ” +
-
”
” + item.ProjectName + ” ” +
-
”
” + item.ManagerName + ” ” +
-
”
” + item.city + ” ” +
- “”;
- $(‘#tblEmployeetbody’).append(rows);
- });
- },
- error: function(ex)
- var r = jQuery.parseJSON(response.responseText);
- alert(“Message: ” + r.Message);
- });
- return false;
- }); <
- /script> <
- styletype = “text/css” >
- .tblEmployee
- font – family: verdana, arial, sans – serif;
- font – size: 11 px;
- color: #333333;
- border-width: 1px;
- border-color: # 666666;
- border – collapse: collapse;
- .EmployeeTableTH
- border – width: 1 px;
- padding: 8 px;
- border – style: solid;
- border – color: #666666;
- background-color: # dedede;
- .EmployeeTableTD
- border – width: 1 px;
- padding: 8 px;
- border – style: solid;
- border – color: #666666;
- background-color: # ffffff;
- } <
- /style>
Now Run Application:
Read more articles on ASP.NET:
Examples:
Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Demo:
Load the JSON data from test.js and access a name from the returned JSON data.
Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data. If an error occurs, log an error message instead.
Transferring Json information to an MVC controller
I am sending Json data to an action method in a simple MVC controller. However, if you utilize the code below, the call is made but the SearchParam is limited to being of type [object], which restricts the use of any value within the searchParam object.
- Passing Json data to MVC controller
- Is it possible for an asp.net MVC “Action Method” to receive JSON without declaring its specific type on the parameter? If so, how?
- Receive parameters in action controller JSON
- ASP.NET MVC: Accept JSON in Action as Anonymous Object
- How to pass a JSON object to an MVC controller?
- How do I get JSON data from a controller action parameter?
- How to send JSON with Ajax () in MVC?
- How to serialize a JSON string into a controller action?
Examples:
Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Demo:
Load the JSON data from test.js and access a name from the returned JSON data.
Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data. If an error occurs, log an error message instead.
Introduction
In this blog, I will demonstrate how to retrieve the data from SQL database using jQuery AJAX in ASP.NET MVC5. I will use jQuery data table for searching, sorting, and paging to HTML table.
Step 1
Open SQL Server 2014 and create a database table.
CREATE TABLE [dbo].[Employees](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Position] [nvarchar](50) NULL,
[Office] [nvarchar](50) NULL,
[Age] [int] NULL,
[Salary] [nvarchar](50) NULL,
[Profile_Image] [nvarchar](100) NULL,
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Step 2
Open Visual Studio 2015, click on New Project, and create an empty web application project.
A New Project one window will appear; select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK. One more window will appear. Choose Empty check on MVC checkbox and click on OK.
Step 3
Click on Tools >> NuGet Package Manager and choose Manage NuGet Packages for Solution. After that, a window will appear. Choose Browse, type bootstrap, and install the package in the project. Similarly, type jQuery, and install the latest version of jQuery package in the project from NuGet. Then, close the NuGet Solution. Keep the useful files in Content and scripts folder.
Step 4
Add Entity Framework, right-click on Models folder, select Add. Then, select New Item and click on it.
After clicking on the New item, you will get a window. From there, select data from the left panel and choose ADO.NET Entity Data Model to give it a name DBModels (this name is not mandatory you can give any name) then click on Add. After you click on Add, a window wizard will open.
Choose EF Designer from database and click Next. After clicking on Next window will appear. Choose a New Connection. Another window will appear. Add your server name. If it is local, then enter dot (.). Choose your database and click on OK. The connection will get added. If you wish to save connect as you want, you can change the name of your connection below.
It will save the connection in web config, then click on Next. After clicking on NEXT, another window will appear. Choose database table name as shown in the below screenshot and click on Finish. Entity framework will be added with the respective class that gets generated under Models folder.
Following class will be added,
namespace MvcJQueryDataTable_Demo.Models
{
using System;
using System.Collections.Generic;
public partial class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public string Office { get; set; }
public Nullable
Age { get; set; }
public string Salary { get; set; }
}
}
Step 5
Right click on Controllers folder select Add then choose Controller. After click on controller, a window will appear. Choose MVC5 Controller-Empty and click on Add. After clicking on Add, another window will appear with DefaultController change the name HomeController then click on Add. HomeController will be added under Controllers folder. Remember don’t change Controller its suffix for all controller change only highlight instead of Default just change Home.
Add following namespace
using MvcJQueryDataTable_Demo.Models;
Complete code of HomeController
using MvcJQueryDataTable_Demo.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace MvcJQueryDataTable_Demo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetData()
{
using (DBModel db=new DBModel())
{
List
employeeList = db.Employees.ToList
();
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
}
}
}
}
Step 6
Right click on Index action method in controller Add view window will appear with default Index name uncheck (use a Layout page) click on Add. As shown in below screenshot, the View will be added in views folder under Home folder with name Index.
Add the following styles and script file in head section of index view,
Write following jquery script to retrieve data from database,
Design the HTML table in index view to display data,
HOW TO RETRIEVE DATA FROM DATABASE USING JQUERY AJAX IN MVC5
Name Position Office Age Salary
Complete index view code
@{
Layout = null;
}
Index
HOW TO RETRIEVE DATA FROM DATABASE USING JQUERY AJAX IN MVC5
Name Position Office Age Salary
Step 7
Run the project by pressing Ctrl +F5.
jQuery – AJAX get() and post() Methods
The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.
ASP.NET MVC: Accept JSON in Action as Anonymous Object
I am sending an Ajax request to a controller action using JSON data, which includes the following
POST
.
$.ajax({ type: "POST", url: "/AssembleProducts/UpdateProduct", data: JSON.stringify({ Product: Product }), contentType: "application/json; charset=utf-8", dataType: 'json' });
The action method looks like below:
[HttpPost] public void UpdateProduct(Product Product) { }
While I can currently accept the JSON data with
Product
, I would prefer to accept it as an Anonymous Object. This way, I would no longer need to use
Type
to accept the data. Despite trying
dynamic
and
object
as parameter types instead of
Product
, I have yet to find any helpful information online.
Please suggest on this situation.
Solution 1:
How about something like this:
Client side:
data: { product: JSON.stringify(Product) }
Server side:
string productJson = HttpContext.Current.Request.Form["product"]; Product p = new JavaScriptSerializer().Deserialize
(productJson);
Solution 2:
To confirm my understanding, am I interpreting this correctly? You possess a Product model.
class Product { public int ProductId { get; set; } public string ProductName { get; set; } // etc }
You intend to upload the item along with supplementary information.
var productJsonObject = { ProductId: 1, ProductName: 'widget', MetaField: 'xyz' }
In case of such a scenario, accessing MetaField in your action can be achieved by directly querying the value provider.
[HttpPost] public void UpdateProduct(Product Product) { var metaField = ControllerContext.Controller.ValueProvider.GetValue("MetaField"); }
jQuery $.post() Method
The
$.post()
method requests data from the server using an HTTP POST request.
Syntax:
The required URL parameter specifies the URL you wish to request.
The optional data parameter specifies some data to send along with the request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the
$.post()
method to send some data along with the
request:
Example
$.post(“demo_test_post.asp”,
name: “Donald Duck”,
city: “Duckburg”
},
function(data, status){
alert(“Data: ” + data + “\nStatus: ” + status);
});
});
The first parameter of
$.post()
is the URL we wish to request (“demo_test_post.asp”).
Then we pass in some data to send along with the request (name and city).
The ASP script in “demo_test_post.asp” reads the parameters, processes them, and returns a result.
The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
Tip: Here is how the ASP file looks like (“demo_test_post.asp”):
dim fname,city
fname=Request.Form(“name”)
city=Request.Form(“city”)
Response.Write(“Dear ” & fname & “. “)
Response.Write(“Hope you live well in ” & city & “.”)
%>
Today, I am going to explain how to get the JSON data with ASP.NET MVC to make AJAX call using jQuery. As we know, JSON is very light-weight as compared to XML or other datasets, so, in this article, I will create a blog system for a demo where first, you will bind the DropDownList with blog categories and on selection of individual category, respective blog details will be populated. For this demonstration, I have used Code First approach. DOWNLOAD CODE To create new ASP.NET MVC application.Open Visual Studio 2015/2013. Go to File menu and select New >> New Project. It will display the following new project window where you can choose different types of project. So, from the right panel, you need to choose Templates >> Visual C# >> Web. After that, from the left panel, you need to choose ASP.NET Web application. Give suitable name to the project as “JSONWithAspNetMVCExample” and click OK.It will open another window where we can choose different templates for ASP.NET applications. So, here we need to go with MVC template and click OK. Create Entity and DataContext Class As in this article, we are using two entities to make blog system, so I am using two entities – category and blog. Basically, the entire categories will display inside the DropDownList and based on the DropDownList value selection, blog details will be binded with html table using jQuery. So, there are two entity classes required. Blog.cs Following is the blog class where properties are defined. I have used Table attribute with class name because for this, it will take same name and a table will be created inside the database when you run the application first. Since we are using Code First approach, model or entity is created first and on the basis of that, database and tables are generated.
- using System;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.ComponentModel.DataAnnotations;
- namespace JsonWithAspNetMVCExample.Models {
- [Table(“NextPosts”)]
- public class Blog {
- [Key]
- public int PostId {
- get;
- set;
- [MaxLength(500)]
- [Column(TypeName = “varchar”)]
- public string PostTitle {
- get;
- set;
- [MaxLength(1000)]
- [Column(TypeName = “text”)]
- public string ShortPostContent {
- get;
- set;
- [Column(TypeName = “text”)]
- public string FullPostContent {
- get;
- set;
- [MaxLength(255)]
- public string MetaKeywords {
- get;
- set;
- [MaxLength(500)]
- public string MetaDescription {
- get;
- set;
- public DateTime PostAddedDate {
- get;
- set;
- public int CategoryId {
- get;
- set;
Category.cs
Following is the category model, where all the properties have defined for blog’s category.
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- namespace JsonWithAspNetMVCExample.Models {
- [Table(“NextCategories”)]
- public class Category {
- [Key]
- [Required(ErrorMessage = “Category is required”)]
- public int CategoryId {
- get;
- set;
- [MaxLength(25)]
- public string CategoryName {
- get;
- set;
So, it is time to create data access classes for Code First approach. I have given it the name “BlogContext” . Inside this class, I have created DbSet for those classes which are participating in blog application. I have also given here the name of database connection [testconnection].
- using System.Data.Entity;
- namespace JsonWithAspNetMVCExample.Models {
- public class BlogContext: DbContext {
- public BlogContext(): base(“testConnection”) {}
- public DbSet < Blog > Blogs {
- get;
- set;
- public DbSet < Category > Categories {
- get;
- set;
Create Database Connection
Now, first I am going to create connection string for database access, which is basically inside the web.config. I have used these names only for testing purposes; you can change it as per your convenience. Be sure before running the application that you have made changes in username and password as per your SQL Server.
Create Blog Controller
When user requests for the particular page in ASP.NET MVC, it first goes to Controller and as per routing configuration, Controller decides which action needs to be executed. So this time, I am going to create a new Controller as “BlogController”.
To create the Controller, right click on Controllers folder from solution and choose Add >> Controller. It will open a popup window where you can provide the name for the Controller and click on Add.
Make changes in BlogController class as following, to get the categories data as well as blogs data based on the category value selection from the database. As you can see with following code, I have used JsonResult GetBlogDetailByCategoryID(int categoryId) which is returning JSON Result.
- using JsonWithAspNetMVCExample.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Mvc;
- namespace JsonWithAspNetMVCExample.Controllers {
- public class BlogController: Controller {
- BlogContext db = null;
- public BlogController() {
- db = new BlogContext();
- public ActionResult Index() {
- List < SelectListItem > blogCategories = new List < SelectListItem > ();
- blogCategories.Add(new SelectListItem {
- Text = “Select Category”, Value = “0”, Selected = true
- });
- var categories = db.Categories.ToList();
- foreach(var c in categories) {
- blogCategories.Add(new SelectListItem {
- Text = c.CategoryName, Value = Convert.ToString(c.CategoryId)
- });
- ViewBag.CategoryList = blogCategories;
- return View();
- public JsonResult GetBlogDetailByCategoryID(int categoryId) {
- List < Blog > blogs = new List < Blog > ();
- blogs = db.Blogs.Where(x => x.CategoryId == categoryId).Take(5).ToList();
- return Json(blogs, JsonRequestBehavior.AllowGet);
I am using Index page where all the categories will bind at the time of loading. So, I have used @Html.DropDownList(“CategoryList”) which will bind the ViewBag categories data on page load and show all the categories inside DropDownList.
To display blog details which belong to selected category in DropDownList, I am making an AJAX call which will directly hit to GetBlogDetailByCategoryID action method on BlogController and get appropriate data to bind it with html table.
Index.html
When you run this application the first time and since we are using Code First Approach, the database and tables will be created automatically. So, when you check the database, there will be a test database created with two tables as NextCategories and NextPosts, as shown in the following image because these names are defined in Model class using table attributes.
These tables are empty. So, you can run the following scripts to insert the dummy data in both the tables.
- Use Test
- Go
- INSERT INTO NextCategories VALUES (‘CSharp’)
- INSERT INTO NextCategories VALUES (‘MVC’)
- INSERT INTO NextCategories VALUES (‘Asp.Net’)
- INSERT INTO NextCategories VALUES (‘HTML’)
- INSERT INTO NextCategories VALUES (‘AngularJS’)
- INSERT INTO NextPosts VALUES (‘CSharp Title 1’, ‘CSharp Short Description 1′,’CSharp Long Description 1’, ‘CSharp Keyword 1’, ‘CSharp Description 1’, GETDATE(), 1 )
- INSERT INTO NextPosts VALUES (‘MVC Title 1’, ‘MVC Short Description 1′,’MVC Long Description 1’, ‘MVC Keyword 1’, ‘MVC Description 1’, GETDATE(), 2 )
- INSERT INTO NextPosts VALUES (‘MVC Title 2’, ‘MVC Short Description 2′,’MVC Long Description 2’, ‘MVC Keyword 2’, ‘MVC Description 2’, GETDATE(), 2 )
- INSERT INTO NextPosts VALUES (‘AngularJS Title 1’, ‘AngularJS Short Description 1′,’AngularJS Long Description 1’, ‘AngularJS Keyword 1’, ‘AngularJS Description 1’, GETDATE(), 5 )
- INSERT INTO NextPosts VALUES (‘HTML Title 1’, ‘HTML Short Description 1′,’HTML Long Description 1’, ‘HTML Keyword 1’, ‘HTML Description 1’, GETDATE(), 4 )
- INSERT INTO NextPosts VALUES (‘CSharp Title 2’, ‘CSharp Short Description 2′,’CSharp Long Description 2’, ‘CSharp Keyword 2’, ‘CSharp Description 2’, GETDATE(), 1 )
- INSERT INTO NextPosts VALUES (‘HTML Title 2’, ‘HTML Short Description 2′,’HTML Long Description 2’, ‘HTML Keyword 2’, ‘HTML Description 2’, GETDATE(), 4 )
- INSERT INTO NextPosts VALUES (‘Asp.Net Title 1’, ‘Asp.Net Short Description 1′,’Asp.Net Long Description 1’, ‘Asp.Net Keyword 1’, ‘Asp.Net Description 1’, GETDATE(), 3)
- INSERT INTO NextPosts VALUES (‘HTML Title 3’, ‘HTML Short Description 3′,’HTML Long Description 3’, ‘HTML Keyword 3’, ‘HTML Description 3’, GETDATE(), 4 )
- INSERT INTO NextPosts VALUES (‘AngularJS Title 2’, ‘AngularJS Short Description 2′,’AngularJS Long Description 2’, ‘AngularJS Keyword 2’, ‘AngularJS Description 2’, GETDATE(), 5 )
- INSERT INTO NextPosts VALUES (‘AngularJS Title 3’, ‘AngularJS Short Description 3′,’AngularJS Long Description 3’, ‘AngularJS Keyword 3’, ‘AngularJS Description 3’, GETDATE(), 5 )
Now, it’s time to run the application to see the output. So, pressF5 and select any category. You will see that corresponding blogs will show under this when you select CSharp as category from DropDownList.
If you select any other blog category, it will show corresponding blog details, as per the following image.
Conclusion
So, today, we learned how to create an ASP.NET MVC application and bind the DropDownList and get JSON result from database tobind it to the html table, using jQuery and Code First approach.
I hope this post will help you. If you have any doubts, please ask your doubts or queries in the comment section. If you like this post, please share it with your friends.
jQuery AJAX is a powerful tool used for sending and receiving data asynchronously from the server without reloading the entire page. In this article, we will demonstrate how to use jQuery AJAX to retrieve JSON data from an Employee class and display it on a view in .NET MVC.
1. Create an Employee class
The first step is to create an Employee class with Name, Email, Age, and Phone properties. You can define the Employee class in your project’s Models folder, as shown below:
public class Employee
{
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
public string Phone { get; set; }
}
2. Create Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetEmployeeData()
{
var employees = new List
{
new Employee { Name = “John Doe”, Email = “[email protected]”, Age = 28, Phone = “123-456-7890” },
new Employee { Name = “Jane Doe”, Email = “[email protected]”, Age = 35, Phone = “234-567-8901” },
new Employee { Name = “Bob Smith”, Email = “[email protected]”, Age = 42, Phone = “345-678-9012” }
};
return Json(employees, JsonRequestBehavior.AllowGet);
}
}
In the code above, we have created a controller called
HomeController
with two actions –
Index()
and
GetEmployeeData()
. The
Index()
action returns the view where we will display the data. The
GetEmployeeData()
action returns the JSON data from the
Employee
class. We have used the
Json()
method to serialize the
employees
list to JSON format and return it as a
JsonResult
. We have also specified the
JsonRequestBehavior.AllowGet
option to allow GET requests.
3. Create an AJAX request
Next, we will create an AJAX request using jQuery. In this example, we will retrieve data from the Employee class and return it in JSON format.
To create the AJAX request, add the following code to your view file or separate Jquery File:
In the code above, we have created an AJAX request using the $.ajax() method. We have specified the URL of the server-side action method that will return the JSON data. We have also specified the HTTP method as GET and the data type as JSON.
4. Display data on the view
In the success callback function of the AJAX request, we will display the data on the view. We will create an HTML table and append the data to the table rows.
To display the data, add the following code to the success callback function:
var html = ”;
$.each(data, function (index, item) {
html += ‘‘;
html += ‘‘ + item.Name + ‘ ‘;
html += ‘‘ + item.Email + ‘ ‘;
html += ‘‘ + item.Age + ‘ ‘;
html += ‘‘ + item.Phone + ‘ ‘;
html += ‘
‘;
});
$(‘#employeeTable’).append(html);
In the code above, we have created an HTML table and used the $.each() method to iterate through the JSON data. We have then created table rows with the employee data and appended them to the table using the append() method.
To display the table on the view, add the following HTML code:
In the code above, we have created an HTML table with headers for the Name, Email, Age, and Phone properties. We have also specified an empty tbody element where we will append the data.
Conclusion
In this article, we have demonstrated how to use jQuery AJAX to retrieve JSON data from an Employee class and display it on a view in .NET MVC. By using AJAX, we can retrieve data from the server without reloading the entire page, resulting in a better user experience.
JSON Data With Asp.Net
This is Asp.Net MVC project for getting JSON data from database using Jquery.
Prerequisities
Visual Studio 2015 SQL Server 2012
Deployment
Download the code. Change the web.config connection string. Run the project. It will run with empty data. Download the “Sql Insert Scripts.sql”. Run it with respect to your database. Run the application again
Authors
Mukesh Kumar : Dotnet-Tutorial.com
License
This project is licensed under the MIT License – see the LICENSE.md file for details
Acknowledgments
Anyone can download and use this code.
Sometimes you may need to load data dynamically based on user input or data based on user selected dropdown list, then you can implement jQuery Ajax call to controller and get JSON data in return and append it to your View, so let’s understand it, how we can achieve it using ASP.NET MVC & jQuery Ajax.
What are we going to Learn?
-> In this article, you will learn how to load get JSON data from MVC controller using jQuery AJAX and then injecting that JSON data into HTML
Step 1: Create a new project in Visual Studio by navigating to File -> New Project -> Web -> ASP.NET web application.
Give a name(jQueryAjaxWithJSON) to your application and Click ‘OK’, then Select ‘MVC’ template to generate default data with your project.
Step 2: Let’s add a Model in ‘Models’ folder, right click on create, Select ‘Add’ then select ‘Class’ and the below class (Products.cs)
public class Products { public string ProductName { get; set; } public string Price { get; set; } }
Step 3: Connect to database using ADO.NET, before we proceed, here is the image of the database which I will be using in this example:
To connect to the database, you need to, Right click on ‘Models’ folder, Select ‘Add’, click ‘New item’ and then from left pane select’Data’, while in the right select ‘ADO.NET Enitty Data model’
Name it as shown in the above image, Click ‘Add’
Click ‘Next’, and then Click on “New Connection”.
In the New tab enter all your details like Server Name, your local DB, username/password and the database to which you have to connect(here ProductsDB) , ‘Test Connection’ if needed
Click “Ok”, then select “Yes, include sensitive data in the connection string”, Click”Next”, now select specific table or all tables rfom the screen
Click ‘Finish’ and you will find the your EDMX created as below
Step 4: Go to your HomeController, In the Index ActionMethod we will create dropdown list using ViewBag to show all Categories Dropdown list, so here the code for it
private ProductsDBEntities dBEntities = new ProductsDBEntities(); public ActionResult Index() { ViewBag.DDL = dBEntities.ProductCategories.ToList(); return View(); }
In your View, to show the dropdown list created above you need to paste Razor syntax as belo
@Html.DropDownList("ProductCategoryDDL", new SelectList(ViewBag.DDL, "Id", "ProductCategoryName",1), new { @class="form-control"})
Now as we need to show Products in the table we will create a HTML tabe, but with empty body, which we will fill with JSON data
@Html.DropDownList("ProductCategoryDDL", new SelectList(ViewBag.DDL, "Id", "ProductCategoryName",1), new { @class="form-control"})
Product Name Price ($)
Right now we have DDL and empty HTML, now to place the data dynamically on changing dropdown list value we will need jQuery AJAX call to controller which will return us JSON data and by looping JSON data and converting it into HTML, we will append it to HTML body
In the above script, after complete page load we are calling ActionMethod ‘Home/GetProducts’ and passing first selected DDL value, which will return Data of selected items, then looping each value, and creating a string of html table row(
Same code, is applied to fetch data on Dropdownlist value change.
So your Complete Index View code will be
@{ ViewBag.Title = "Home Page"; } @Html.DropDownList("ProductCategoryDDL", new SelectList(ViewBag.DDL, "Id", "ProductCategoryName",1), new { @class="form-control"})
Product Name Price ($) @section scripts{
}
In your HomeController, let’s create the ActionMethod which return JSON data to the AJAX
public JsonResult GetProducts(int id) { var Products = dBEntities.ProductsMainTables.Where(a => a.ProductCategoryId == id) //Select items in new class to avoid circular reference error .Select(a=> new Products { Price=a.Price , ProductName=a.ProductName }) .ToList(); //do not forget to add JsonRequestBehavior.AllowGet as our request is GET request, //otherwise you may get error return Json(Products,JsonRequestBehavior.AllowGet); }
Note: To stay away from JSON error like Circular reference we have created elements of New Products class and selected ProductName & Price only
Step 5: Build your project, you will see screen like below
on changing dropdown list you may see that table body data changes, here is the image with console view of the browser
Complete working output, sample
Please feel free to ask questions related to it, if you have any doubts, thanks
Keywords searched by users: get json data using jquery in mvc
Categories: Tìm thấy 41 Get Json Data Using Jquery In Mvc
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/