I was working to use Kendo Grid in asp.net mvc4.Here is the code written in contrller and view.But i am not getting the Kendo Grid in output.Can anyone help me with this?
I have used ADO.NET entity model to form class called Contacts to connect to the database
and in the controller i have converted the data coming from Contacts class to json.
Controller:
public class HomeController : Controller
{
public PersonaEntities db = new PersonaEntities();
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[HttpGet]
public JsonResult Getjsondata()
{
ViewBag.Title = "Hello World";
JsonResult jsonResult = new JsonResult();
var Contacts = db.Contacts.ToList();
jsonResult.Data = Contacts;
return Json(jsonResult,JsonRequestBehavior.AllowGet);
}
Then i have tried in the view to display kendo grid by giving its datasource as controller action method.But I am not getting the output as kendo grid.
View:
#{
ViewBag.Title = "Getjsondata";
}
<h2>Getjsondata</h2>
<link href="~/Content/kendo/2014.2.716/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo/2014.2.716/kendo.dataviz.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/2014.2.716/angular.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/jquery.min.js"></script>
<script src="~/Scripts/kendo/2014.2.716/kendo.all.min.js"></script>
<script>
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: { read: { url: "Home/Getjsondata", dataType: "json" } },
schema: {
data: function (data) {
return data;
}
}
})
$("#Grid").kendoGrid({
dataSource: dataSource,
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The Json method encapsulated the data into a JsonResult already. Your reposonse is double-wrapped. Pass the data directly into the Json method.
You'll need two actions, one for the static view and one for the JsonResult:
public class HomeController : Controller
{
public ActionResult GridView()
{
return this.View();
}
public JsonResult Getjsondata()
{
var Contacts = db.Contacts.ToList();
return Json(Contacts, JsonRequestBehavior.AllowGet);
}
}
For the view, you need a GridView.cshtml:
#* css and js imports omitted *#
<script>
$(document).ready(function () {
$("#Grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: '#Url.Action("Getjsondata")',
type: 'GET', // should be POST, though
}
},
schema: {
type: "json",
model: {
id: "id",
fields: {
'id' : { type: 'number', editable: false},
'fname': { type: 'string' },
'lname': { type: 'string' },
'phone': { type: 'string' }
}
}
}
},
columns: [
{
field: "id",
title: "id"
},
{
field: "fname",
title: "fname"
},
{
field: "lname",
title: "lname"
},
{
field: "phone",
title: "phone"
}
]
});
});
</script>
<div id="Grid"></div>
The url of the page is ~/Home/GridView. When you open the page, the controller only returns the static page GridView.cshtml. Once the page is loaded on the client side (your browser), the JavaScript code will run and make an AJAX request to the ~/Home/Getjsondata action to load the data for the kendo grid.
I found out that i was loading the script jquery.js manually which i think gets loaded by default in browser.Also i found that scripts and css files need to be mentioned only in shared layout file and not necessary to mention it in view.
jquery asp.net-mvc
Related
My goal is:
I am trying to send values into a method of my controller to update the database (which is connected remotely via API).
I have checked several tutorials (How to pass parameters in $ajax POST? for example) but I can not send the data in my controller I have a 500 error that is due to my ajax call.
Could you tell me what to do?
View
$(document).ready(function () {
$.ajax({
url: "http://localhost:44338/Registration/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
Controller
[Authorize]
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.RegisterForm rF)
{
try
{
var test = rF.id;
Ok("success");
}
catch (Exception e)
{
Console.Write(e.Message);
return BadRequest();
}
return View();
}
Model
public class RegisterForm
{
public string id { get; set; }
}
Create Model first now(Standard Way)
Try this and let me know.
public class InfoModel
{
public string id { get; set; }
//Add your model fields here
}
Your Api
[HttpPost]
public async Task<ActionResult> ShowRegistration(InfoModel im)
{
//code
}
Your ajax call test this and then send more data:
$.ajax({
url: "url",
type: 'POST',
data: JSON.stringify({"id": id}),
contentType: 'application/JSON',
success: function (data) { },
error: function () {};
})
Tested Example:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:62211/Home/ShowRegistration",
type: 'POST',
data: JSON.stringify({ "id": 1 }),
contentType: 'application/JSON',
success: function (data) { },
error: function () { }
})
});
</script>
</head>
<body>
</body>
</html>
Api
using System.Threading.Tasks;
using System.Web.Mvc;
namespace WebApplication5.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public async Task<ActionResult> ShowRegistration(Models.info inf)
{
// Access inf.id
return null;
}
}
}
I'm a beginner & I'm trying to develop a autocomplete search box with ASP.Net MVC 5. I use Northwind Database and Entity Framework 6.
Here is my index.cshtml code
#model IEnumerable<AutoComplete3.Models.Customers>
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("GetCustomers")'
});
});
</script>
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Here is my CustomerController class
public class CustomersController : Controller
{
northwindEntities db = new northwindEntities();
public ActionResult Index()
{
return View(db.Customers);
}
[HttpPost]
public ActionResult Index(string SearchTerm)
{
List<Customers> customers;
if (string.IsNullOrEmpty(SearchTerm))
{
customers = db.Customers.ToList();
}
else
{
customers = db.Customers.Where(c => c.CompanyName.StartsWith(SearchTerm)).ToList();
}
return View(customers);
}
public JsonResult GetCustomers(string term)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
}
This code is working when i am searching records, by entering keyword & clicking submit button. But the GetCustomer method cannot be called by the jquery script. Inspect Elements shows following error.
Uncaught TypeError: $(...).autocomplete is not a function
The text box should be suggest Company Names to the textbox itself. How to correct this.
Thanks.
Javascript
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetCustomers","Home")',
type: "POST",
dataType: "json",
data: { searchTerm: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CompanyName, value: item.CompanyName };
}))
}
})
},
messages: {
noResults: "", results: ""
},
});
})
View
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Controller
Please update your controller with [HttpPost]
[HttpPost]
public JsonResult GetCustomers(string searchTerm)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
I have asp.net mvc 5 application but I can't get this fairly simple script to work. I am new to this MVC (I am WebForms guy).
Basically jQuery is not attaching .click() event to the button to post data to the underlying controller.
Can somebody pinpoint what I am doing wrong?
The View (HelloWorld/Index.cshtml):
#model HelloWorld.Models.HelloWorldModel
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
</head>
<body>
<div>
#using (Html.BeginForm("Welcome","HelloWorld",FormMethod.Post, new {id = "myhelloform"})){
<span>Name:</span>
#Html.TextBoxFor(model=> model.Name)
<button id="btnPost" type="button">Post</button>
}
</div>
<script>
var testform = function () {
var init = function () {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
};
var submitForm = function () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
}
});
};
return {
Init: init
};
};
</script>
</body>
</html>
</html>
The Controller (Controllers/HelloWorldController.cs):
using System.Web.Mvc;
namespace HelloWorld.Controllers
{
public class HelloWorldController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Welcome()
{
return Json("test");
}
}
}
The Model (Models/HelloWorldModel.cs)
namespace HelloWorld.Models
{
public class HelloWorldModel
{
public string Name { get; set; }
}
}
Delete the variables testform and init and it works (Also need to use $( document ).ready as #Tbseven mentions):
$( document ).ready(function() {
$("#btnPost").on("click", function ()
{
alert("anybody there??");
});
});
Fiddle: https://dotnetfiddle.net/HCdFXM
You have to place your jquery code inside next function:
$( document ).ready(function() {
// Here
});
$( document ).ready(function() {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
function submitForm () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
});
};
});
You can use input instead of button and there is no need to add click event for that.
<input type="submit" id="btnPost" />
so Iam new on this and I have a Ajax.ActionLink that work fine but can't understand (why I have to put the div "linkEdit" in my list view and in the partial view)
so have Ajax.ActionLink in my list view of solution (and when select a solution it get me all the product) and it goes to a action to
[HttpGet]
[Ajax(true)]
[ActionName("Index")]
public ActionResult Index_Ajax(Int32? id)
{
// to do = load the product that solution have
return PartialView("SolutionProduct", viewModel);
}
the Ajax.ActionLink
#Ajax.ActionLink("Select", "Index", "solution",
new { id = item.solutionId },
new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "linkEdit",
InsertionMode = InsertionMode.Replace
})|
i have this div in a partial view "SolutionProduct" and in my list view
<div id="linkEdit">
<table>
<tr>
<th>Nombre de Producto</th>
</tr>
#foreach (var item in Model.Productos)
{
<tr >
<td>
#item.Nombre
</td>
</tr>
}
</table>
}
</div>
so my question would be why if I take out the div on my list view it doesnt work?
I am going to share here different examples of using AJAX in ASP .NET MVC 4.
1) Use an Internet Application template to create ASP .NET MVC 4 project in Visual Studio 2012.
2) Under the folder Models create this simple class
public class Person
{
public string FirstName { set; get; }
}
3) Add following code to public class HomeController : Controller
[AcceptVerbs("POST")]
public bool MethodWithoutParameters()
{
bool allow = true;
if (allow)
{
return true;
}
else
{
return false;
}
}
[AcceptVerbs("POST")]
public string MethodWithParameters(string id)
{
return id + " i got it, man! ";
}
[AcceptVerbs("GET")]
public ActionResult GetSomeName()
{
var data = new { name = "TestName " };
return Json(data, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs("POST")]
public ActionResult PerformAction(FormCollection formCollection, Person model)
{
model.FirstName += "Well done! Form 1";
return Json( model.FirstName);
}
[AcceptVerbs("POST")]
public ActionResult PerformAction2(FormCollection formCollection, Person model)
{
model.FirstName += "Well don! Form 2";
return Json(model.FirstName);
}
public JsonResult DeleteFile(string fileName)
{
var result = fileName + " has been deleted";
return Json(result, JsonRequestBehavior.AllowGet);
}
4) Replace all code within Index.cshtml with the following one (Perhaps, instead of MvcApplication1 you have to use your real application name...)
#model MvcApplication1.Models.Person
#{
ViewBag.Title = "Home Page"; } #section featured {
}
MethodWithoutParameters
MethodWithParameters
'parameter00001'
#using (Ajax.BeginForm("PerformAction", "Home", new AjaxOptions {
InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess
= "OnSuccess", OnFailure = "OnFailure" })) {
This is a demo form1.
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
}
#using (Ajax.BeginForm("PerformAction2", "Home", new AjaxOptions {
InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess
= "OnSuccess2", OnFailure = "OnFailure2" })) {
This is a demo form2.
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, null, new { #class = "labelItem" })
}
cat.png
Delete File
function DeleteFile() {
var fn = $('#fileNameLabel').html();
$.ajax({
url: "Home/DeleteFile", //check this.href in debugger
dataType: "text json",
type: "POST",
data: { fileName: fn }, //pass argument here
success: function (data, textStatus) {
if (data) {
if (textStatus == 'success') {
$('#fileNameLabel').html(data);
$('#btnDeleteFile').hide();
}
else {
alert('error');
}
} else {
alert('error');
}
}
});
}
function OnSuccess(response) {
$('#form1').html(response);
}
function OnFailure2(response) {
alert("Error Form 2");
}
function OnSuccess2(response) {
$('#form2').html(response);
}
function OnFailure(response) {
alert("Error Form 1");
}
function MethodWithoutParameters() {
var url = "Home/MethodWithoutParameters";
$.post(url, function (data) {
if (data) {
alert(data);
} else {
alert('error');
}
});
}
function MethodWithParameters(id) {
var url = "Home/MethodWithParameters/" + id;
// alert(url);
$.post(url, function (data) {
if (data) {
alert(data);
} else {
alert('error');
}
});
}
$(document).ready(function () {
$.getJSON("Home/GetSomeName",
null,
function (data) {
if (data) {
$('#UserNameLabel').html(data.name);
} else {
alert('error');
}
}
);
}); </script>
5) Make sure that header of the _Layout.cshtml looks like
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"
type="text/javascript">
6) And everything should work fine.
I hope all those samples will help you!
You have to put the div with an id of "linkEdit" into your list view as that is the portion of the page that is to be replaced by the result returned by the ajax link.
ASP.NET AJAX enables a Web application to retrieve data from the server asynchronously and to update parts of the existing page. This improves the user experience by making the Web application more responsive.
And is this case you are using the InsertionMode
InsertionMode = InsertionMode.Replace
so you will need a div with the id of "linkEdit" in both your list view and partial view.
I have this string variable call "status" which is updated by a serial port connection I've made. the "status" show's if u are connected to the serial port or not.
I've made a simple 2 buttons view. one opens the connection and the other close it.
i want to be able to auto update the status of the connection inside the view.
i guess i need to use some kind of timer which shows the string inside "status" every given time, but i have no clue on how to do it..
This is my HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult CheckStatus()
{
return Json(new { status = "active" });
}
}
and this is my view:
<script type="text/javascript">
$(function() {
// poll every 5 seconds
setInterval('checkStatus()', 5000);
}
function checkStatus() {
$.ajax({
url: 'Home/CheckStatus',
type: 'POST',
dataType: 'json',
success: function(xhr_data) {
if(xhr_data.status == 'active') {
// this would just disable the "Open" button
$('#btnOpen').attr('disabled', 'disabled');
}
}
});
}
I'm going to assume you can use jQuery, and that you have a Controller action that looks like this:
[HttpPost]
public class StatusController : Controller
{
public JsonResult CheckStatus()
{
return Json(new { status = "active" });
}
}
Then, in your view add the following script
<script type="text/javascript">
$(function() {
// poll every 5 seconds
setInterval('checkStatus()', 5000);
}
function checkStatus() {
$.ajax({
url: 'Status/CheckStatus',
type: 'POST',
dataType: 'json',
success: function(xhr_data) {
if(xhr_data.status == 'active') {
// this would just disable the "Open" button
$('#btnOpen').attr('disabled', 'disabled');
}
}
});
}
</script>