I'm facing a problem when doing
http://www.jeasyui.com/tutorial/app/crud/index.html
After I saved the new item, I've successfully update the database, but when the javascript calling saveUser function to close the dialog box and refresh the grid, I always got this error:
Uncaught SyntaxError: Unexpected token )
at HTMLFormElement.success (http://localhost:58137/scripts/scripteasyui.js:22:44)
at HTMLIFrameElement.cb (http://www.jeasyui.com/easyui/jquery.easyui.min.js:7707:14)
at HTMLIFrameElement.handle (http://code.jquery.com/jquery-1.6.min.js:16:32793)
at HTMLIFrameElement.k (http://code.jquery.com/jquery-1.6.min.js:16:29553)
I'm using MVC c#, here's my code:
For the head on the view html
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/color.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
<script src="~/scripts/scripteasyui.js"></script>
for the scripteasyui.js file:
var url;
function newBrand() {
$('#dlg').dialog('open').dialog('center').dialog('setTitle', 'New User');
$('#fm').form('clear');
url = 'SaveBrands';
}
function editBrand() {
var row = $('#dg').datagrid('getSelected');
if (row) {
$('#dlg').dialog('open').dialog('center').dialog('setTitle', 'Edit User');
$('#fm').form('load', row);
url = 'update_user.php?id=' + row.id;
}
}
function saveBrand() {
$('#fm').form('submit', {
url: url,
onSubmit: function () {
return $(this).form('validate');
},
success: function (result) {
var result = eval('(' + result + ')');
if (result.errorMsg) {
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
function destroyBrand() {
var row = $('#dg').datagrid('getSelected');
if (row) {
$.messager.confirm('Confirm', 'Are you sure you want to destroy this user?', function (r) {
if (r) {
$.post('destroy_user.php', { id: row.id }, function (result) {
if (result.success) {
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.errorMsg
});
}
}, 'json');
}
});
}
}
for the save method on the controller
public void SaveBrands()
{
string brandid = Request.Form["brandid"];
string brandname = Request.Form["brandname"];
using (ItemsEntities db = new ItemsEntities())
{
db.Brands.Add(new Brand { BrandID = brandid, BrandName = brandname });
db.SaveChanges();
}
}
For showing the list data
public JsonResult ShowBrands(string sidx, string sort, int page, int rows)
{
sort = (sort == null) ? "" : sort;
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
using (ItemsEntities db = new ItemsEntities())
{
var brandqry = db.Brands.OrderBy(e => e.BrandID);
int RecCount = brandqry.Count();
var totalPages = (int)Math.Ceiling((float)RecCount / (float)rows);
var jsonData = new
{
total = totalPages,
page,
records = RecCount,
rows = brandqry.ToList(),
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
I found the answer I need to serialized the result into jason for the result parameter on javascript
string jsondata = JsonConvert.SerializeObject(brandmdl);
return Json(jsondata);
Related
I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}
I'm trying to display some data in Google Charts but get this error:
Data column(s) for axis #0 cannot be of type string..
I have two properties from this class:
public class GAStatistics
{
public string Date { get; set; }
public string Visitors { get; set; }
}
I'm passing this a list of these properties from this controller:
public class GAStatisticsController : Controller
{
//GET: /ShopStatistics/
public ActionResult GetData()
{
return Json(CreateCompaniesList(), JsonRequestBehavior.AllowGet);
}
private IEnumerable<GAStatistics> CreateCompaniesList()
{
List<GAStatistics> ListGaVisitors = new List<GAStatistics>();
foreach (var row in d.Rows)
{
GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
ListGaVisitors.Add(GaVisits);
}
return ListGaVisitors;
}
}
To this view of which I pass the list from the controller:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/GAStatistics/GetData', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Date');
tdata.addColumn('string', 'Visitors');
for (var i = 0; i < data.length; i++) {
//tdata.addRow([data[i].Year, data[i].Salary, data[i].Expense]);
tdata.addRow([data[i].Date, data[i].Visitors]);
}
var options = {
title: "Expenses, salary For the current year"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
chart1.draw(tdata, options);
});
}
</script>
Any idea?
I have tested your example and found out that the main issue is because the second column Visitors should be a number instead of a string.
I have replaced the column type in the tdata.addColumn('number', 'Visitors'); line and added parseInt inside the loop:
tdata.addColumn('date', 'Date');
tdata.addColumn('number', 'Visitors');
// sample data: var data = [{ Date: "20140124", Visitors: "873" }, { Date: "20140125", Visitors: "875" }];
for (var i = 0; i < data.length; i++) {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4,2) + "-" + data[i].Date.substr(6,2);
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
Also the first column Date could have remained a string, but I replaced its type to be date and added new Date conversion as well.
I have got problem with displaying employee details in view when the user clicks the button on view..
when the user clicks the button the employee details(both id and name) will be called through the JSON and displaying data in html table, for that purpose I have written like this in my view
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<table id ="parenttable"></table>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
and this is my controller, here i am returning json data to view
namespace MvcSampleApplication.Controllers
{
public class EmpDetailsController : Controller
{
[HttpGet]
public ActionResult GetEmployees()
{
List<EmployeeClass> employees = new List<EmployeeClass>();
EmployeeClass employee1 = new EmployeeClass { EmployeeId=1, EmployeeName = "Rams"};
EmployeeClass employee2 = new EmployeeClass { EmployeeId = 2, EmployeeName = "joseph" };
EmployeeClass employee3 = new EmployeeClass { EmployeeId = 3, EmployeeName = "matt" };
employees.Add(employee1);
employees.Add(employee2);
employees.Add(employee3);
return Json(employees, JsonRequestBehavior.AllowGet);
}
}
}
but I am getting http 404 resource not found error, when i am trying to access this url
http://localhost/EmpDetails
would any one pls suggest any ideas and any suggestions on this,that would be very greatful to me..
Many thanks...
Modified View
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = #Url.Action("GetEmployees","EmpDetails")
//alert("hi");
$.getJSON(url, function (data) {
//alert("hi");
$.each(data, function (Val) {
var user = '<tr><td>' + Val.EmployeeId + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false;
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<div class="temptable">
<table id ="parenttable"></table>
</div>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
I am not able to hit second Alert Function inside JavaScript function.
You forgot to cancel the default action of the button by returning false from the click handler:
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false; // <!-- This is very important
});
By not canceling the default action, when you click on the submit button, the browser submits the form and redirects away from the page to the action of the form leaving no time for the AJAX request to ever execute.
Try using this as your url #Url.Action("GetEmployees","EmpDetails")
Try this
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
$.ajax({
url: 'GetEmployees',
type: 'POST',
data: JSON.stringify({ table: table }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var rowcount = data.employees.length;
for (var i = 0; i < rowcount; i++) {
var user = '<tr><td>' + employees[i].EmployeeId + employees[i].EmployeeName + '<tr><td>'
table.append(user);
}
});
},
error: function () {
alert('fail');
}
});
return false;
});
I am working on jQuery fileupload now here I am saving images once saved some data I need to post to my page
Here I have two applications (two separate applications) html.page to I am posting images to mvc upload controller and I had saved the image success fully
Now to get the respose data I need to redirect through url so I am redirecting through like this
public void ReturnResult(string jsonObj)
{
var hostName = " http://localhost:8988/cors/postmessage.html?MyURL=";
var s = jsonObj;
var filterUrl = hostName + s;
HttpContext.Current.Response.Redirect(filterUrl);
}
Once redirection to this page how could I get those data?
And I don't have any idea is this redirecting the data or not how could could I know that
data is redirecting or not could u plz help me get the data
this is my
redirected to this page
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery File Upload Plugin postMessage API</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>
'use strict';
var origin = /^http:\/\/example.org/,
//var origin = 'http://localhost:4071/Upload/UploadHandler.ashx',
target = new RegExp('^(http(s)?:)?\\/\\/' + location.host + '\\/');
alert(1);
alert(origin);
$(window).on('message', function (e) {
e = e.originalEvent;
var s = e.data,
xhr = $.ajaxSettings.xhr(),
f;
if (!origin.test(e.origin)) {
throw new Error('Origin "' + e.origin + '" does not match ' + origin);
}
if (!target.test(e.data.url)) {
throw new Error('Target "' + e.data.url + '" does not match ' + target);
}
$(xhr.upload).on('progress', function (ev) {
ev = ev.originalEvent;
e.source.postMessage({
id: s.id,
type: ev.type,
timeStamp: ev.timeStamp,
lengthComputable: ev.lengthComputable,
loaded: ev.loaded,
total: ev.total
}, e.origin);
});
s.xhr = function () {
return xhr;
};
if (!(s.data instanceof Blob)) {
f = new FormData();
$.each(s.data, function (i, v) {
f.append(v.name, v.value);
});
s.data = f;
}
$.ajax(s).always(function (result, statusText, jqXHR) {
if (!jqXHR.done) {
jqXHR = result;
result = null;
}
e.source.postMessage({
id: s.id,
status: jqXHR.status,
statusText: statusText,
result: result,
headers: jqXHR.getAllResponseHeaders()
}, e.origin);
});
});
</script>
</body>
</html>
Any help will greately appreciated thanks in advance
If you need to get data from the query string returned from the controller in your HTML page then you can use this function.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
you can get you values on page load like:
var MyURL= getUrlVars()['MyURL'];
In my asp.net mvc3 page, i am using jquery to show a calender to display the events added in the database. Its working fine in google chrome but its showing below error in firefox 19.0.2
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.8.3.js")"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-i.css">
<link rel="stylesheet" href="../../Content/css/styleui.css" />
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Page/dates", null, function (data) {
var s = eval(data);
alert(s);
showevents(s);
});
function showevents(events) {
$("#datepicker").datepicker({
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
alert(event.Title);
}
}
});
}
});
</script>
<div id="datepicker">
[16:35:16.336] ReferenceError: event is not defined # http://code.jquery.com/jquery-1.8.3.js:579
You are probably missing var event; at the start of showevents function. See comments:
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
// event is not defined
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
// event is not defined
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
// event is not defined
alert(event.Title);
}
}