I am not sure what I am doing wrong
My HTML
<head>
<title></title>
<script src="include/libraries/jquery/jquery-2.2.2.min.js"></script>
<script src="include/libraries/jquery/jquery-2.2.2.intellisense.js"></script>
<script src="include/libraries/jquery/jquery-2.2.2.js"></script>
<link href="include/libraries/kendo/css/kendo.bootstrap.min.css" rel="stylesheet" />
<link href="include/libraries/kendo/css/kendo.common-bootstrap.min.css" rel="stylesheet" />
<script src="include/libraries/kendo/js/kendo.all.js"></script>
<script src="include/libraries/kendo/js/kendo.all.min.js"></script>
<script src="include/libraries/kendo/js/kendo.aspnetmvc.min.js"></script>
<script src="include/libraries/kendo/js/kendo.custom.min.js"></script>
<script src="include/libraries/kendo/js/kendo.timezones.min.js"></script>
<meta charset="utf-8" />
</head>
<body>
<div id="grid">
<div class="demo-section k-content wide">
<div>
<h4>Add or update a record</h4>
<div data-role="grid"
data-editable="true"
data-toolbar="['create', 'save']"
data-columns="[
{ 'field': 'CourseID' },
{ 'field': 'CourseName' },
{ 'field': 'IsActive' },
]"
data-bind="source: courses,
visible: isVisible,
events: {
save: onSave
}"
style="height: 200px"></div>
</div>
</div>
<script>
var viewModel = kendo.observable( {
isVisible: true,
onSave: function(e) {
kendoConsole.log("event :: save(" + kendo.stringify(e.values, null, 4) + ")");
},
courses: new kendo.data.DataSource({
schema: {
model: {
id: "CourseID",
fields: {
CourseID: { type: "number" },
CourseName: { type: "string" },
IsActive:{type:"boolean"}
}
}
},
batch: true,
transport: {
read: {
type:"GET",
url: "http://localhost:51447/api/Courses",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
}
})
});
kendo.bind($("#grid"), viewModel);
</script>
</div>
</body>
My Controller Code
// GET: api/Courses
public IQueryable<object> GetCourses()
{
return db.Courses.Select(
o => new
{
CourseID = o.CourseID,
CourseName = o.CourseName,
IsActive = o.IsActive
});
//}).Where(l => l.IsActive == false);
}
My JSON
[{"CourseID":1,"CourseName":"Beauty Therapy","IsActive":true},{"CourseID":2,"CourseName":"Software Development","IsActive":true},{"CourseID":3,"CourseName":"Bookkeeping and Accounting","IsActive":true}]
I finally got this fixed. The structure of my solution is such that it has a WebAPI and a Web app. So in the WebApiConfig.cs file I added the line config.EnableCors(); and it worked.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Related
I want to use Ajax in ASP.NET Core, but the request does not go to the controller. I use VS 2017 and ASP.NET Core 2.1.
View:
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.7.0/d3.min.js"></script>
<script>
$(document).ready(function () {
$('#buttonDemo1').click(function () {
$.ajax({
type: 'GET',
url: '/demo/demo1',
success: function (result) {
$('#result1').html(result);
}
});
});
})
</script>
<fieldset>
<legend>
<form>
<input type="button" value="demo1" id="buttonDemo1" />
<br />
<span id="result1">
</span>
</form>
</legend>
</fieldset>
Controller:
[Route("Demo1")]
public IActionResult Demo1()
{
return new JsonResult("DEmo1");
}
Startup.cs:
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
update:
I test this code and
it work in my Project:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Demo/demo1", true);
xhttp.send();
}
</script>
Thanks for help
There is probably a problem with the relative URL: I would generate the URL with the URL Action Helper from c# In your view:
<script>
$(document).ready(function () {
var url = '#Url.Action("Demo1", "Demo")';
$('#buttonDemo1').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (result) {
$('#result1').html(result);
}
});
});
});
</script>
I am pretty new to asp.net so I tried to add a simple bar chart with charts.js to my view but all I get is an empty page.
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<string> iData = new List<string>();
List<string> iData2 = new List<string>();
iData.Add("Sam");
iData2.Add("555");
iData.Add("Alex");
iData2.Add("666");
iData.Add("Michael");
iData2.Add("777");
ViewBag.Value_List = iData2;
ViewBag.Name_List = iData;
return View();
}
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Charts</title>
<script src="~/Scripts/Chart.min.js"></script>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
var barChartData =
{
labels: [#Html.Raw(ViewBag.Name_List)],
datasets: [{
label: 'ChartTest',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [#ViewBag.Value_List]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'bar',
data: barChartData,
options:
{
title:
{
display: true,
text: "ChartTest"
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
</head>
<body>
<div style="text-align: center">
<canvas id="barcanvas"></canvas>
</div>
</body>
</html>
I tried to help me with some tutorials but nothing worked for me.
Can someone tell me what I am doing wrong?
Two changes needed:
Serialize the data into JSON in the controller:
using System.Web.Script.Serialization;
var js = new JavaScriptSerializer();
ViewBag.Value_List = js.Serialize( iData2);
ViewBag.Name_List = js.Serialize(iData);
Remove the extra square brackets in the view:
labels: #Html.Raw(ViewBag.Name_List),
data: #Html.Raw(ViewBag.Value_List)
You need to create "drop in" JavaScript to represent the data.
labels: ["555","666","777"] ,
data: ["Sam","Alex","Michael"]
I am developing an ASP.Net MVC5 project and I am calling a webservice in my project with ajax. Every thing is ok so far and at the end the city names can be appended into the select tag, but the code below doesn't work:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function f1() {
var token="";
$.ajax({
data: { webservice_username: 'webservice_usernam', password: 'password' },
url: 'http://www.travelinsure.ir/api/v1.1/authenticate',
type: 'POST',
dataType: 'json',
success: function (data) {
$.each(data, function (idx, result) {
token = result;
f2(result);
})
},
error: function (x, y, z) {
alert(x.responseText);
alert(z);
}
});
}
function f2(token) {
// alert('New: '+token);
$.ajax({
data: { token: token },
url: 'http://www.travelinsure.ir/api/v1.1/getcitylist?token=',
type: 'GET',
dataType: 'json',
success: function (data) {
results = JSON.stringify(data);
// a = JSON.parse(data);
alert(results);
a = $.parseJSON(data);
alert(a);
$.each(data, function (idx, r) {
$("#sel").append("<option value='" + r.city_id + "'>'" + r.city_name + "'</option>");
alert(result.city_name);
})
},
error: function (x, y, z) {
alert(x.responseText);
alert(z);
}
});
}
</script>
</head>
<body>
<div>
<input type="submit" name="name" value="Click!!!" onclick="f1()" />
</div>
<div id="mydiv">
<select id="sel">
<option>لیست شهرهای ایران</option>
</select>
</div>
</body>
</html>
Looks like you are appending the option in the wrong way.
Do it like this:
$.each(data, function(key, value) {
$('#sel').append($("<option></option>").attr("value",item.city_id).text(item.city_name));
});
You could also add a new option like this:
$.each(data, function (key, item) {
$("#sel").get(0).options[$("#sel").get(0).options.length] = new Option(item.city_name, item.city_id);
});
I have successfully written a MVC4 webapi that takes CompanyID, name and posts it to DB. I need to change it in such a way that the user can enter multiple values for CompanyID with their Names and Save it to DB in one shot. How can I do that? Here's my code
--Index.cshtml
<div id="body">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Welcome Web API!</h1>
</hgroup>
</div>
</section>
<section class="content-wrapper main-content clear-fix">
<p>
For API documentation: #Html.ActionLink("API", "Index", "Help", new { area = "" }, null)
</p>
<p>
Update/Insert Company info: Click Here!
</p>
</section>
</div>
--Companies.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<script>
var overrides = Array();
function parseform(button) {
var CompanyID = $("#CompanyID").val();
var CompanyName = $("#CompanyName").val();
var lst = {
CompanyID: CompanyID,
CompanyName: CompanyName
}
if (button.attr('value') === "POST") {
console.log("posting : " + lst.toString());
postdata(lst);
} else {
console.log("ERROR");
}
}
function postdata(lst) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/Company/",
data: lst,
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
console.log(status);
$("#response").text(status)
},
error: function (xhr, status, error) {
console.log(xhr.responseText);
var json = jQuery.parseJSON(xhr.responseText);
console.log(json);
$("#response").text(status)
alert(json.Message);
}
});
}
$(document).ready(function () {
$('input:button').click(function () {
parseform($(this));
});
});
</script>
<div id="form">
<label for="CompanyID">CompanyID:</label><input type="text" id="CompanyID" /><br />
<label for="CompanyName">CompanyName:</label><input type="text" id="CompanyName" /><br />
<input type="button" id="Post" value="POST"/>
</div>
<div id="response">
</div>
</body>
</html
In CompaniesController, I have written a call to stored procedure for the POST method to save one record at a time.
How can I Post many rows at a time & what changes should I do to html file.
Thanks
R
How did you declared your variables in your Model. For operating multivalued types, try something like this:
private ICollection<string> _variable;
public ICollection<string> VariableName
{
get
{
if (_variable == null)
{
return new Collection<string> {""};
}
else
{
return _variable;
}
}
set { _variable = value; }
}
On Page 1 I get the object I need:
ProjectSearchCriteria = (GBLProjectSearchCriteria)Session[GblConstants.SESSION_PROJECT_SEARCH_CRITERIA];
I'm trying to pass this to an API on a page load of Page 2.
Page 2:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<link href="../x.css" type="text/css" rel="stylesheet">
<link href="../Content/kendo.common.min.css" rel="stylesheet" />
<link href="../Content/kendo.default.min.css" rel="stylesheet" />
</head>
<body>
<form id="frmProjectSearchResults" runat="server">
</form>
<script src="../Scripts/ProjectsTreeView.js"> </script>
<script type="text/javascript">
CreateProjectTree(<%= ProjectSearchCriteria %>);
</script>
</body>
</html>
And this is the JavaScript function:
function CreateProjectTree(searchCriteria)
{
debugger;
var projects = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/projects?searchcriteria =" + searchCriteria,
contentType: "application/json"
},
parameterMap: function (data, operation) {
return JSON.stringify(data);
}
},
schema: {
model: {
children: "seasons"
}
}
});
$("#treeview").kendoTreeView({
dataSource: projects,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["Title"],
select: treeviewSelect
});
function treeviewSelect(e) {
var node = this.dataItem(e.node);
window.open(node.NotificationLink, "_self");
}
}
Can anyone help me understand what I'm doing wrong?
Maybe this:
<script type="text/javascript">
CreateProjectTree("\"" + <%= ProjectSearchCriteria %> + "\"");
</script>