Unable to update webpage with database notifications realtime with SignalR - javascript

I am working on a web application developed using Asp.Net MVC which on which I have a page on which data gets updated at realtime whenever data is modified on the database. I have some source on line and tried to implement this feature but it resulted in huge invalid data on the webpage.
I am using SQL dependency and SignalR to achieve this as follows
In Global.asax, I have the following
protected void Application_Start()
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
protected void Application_End()
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
and in Models section I have the following classes
public class JobInfo
{
public int JobID { get; set; }
public string Name { get; set; }
public DateTime LastExecutionDate { get; set; }
public string Status { get; set; }
}
public class JobInfoRepository
{
public IEnumerable<JobInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [JobID],[Name],[LastExecutionDate],[Status]
FROM [dbo].[JobInfo]", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo(){
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3) }).ToList();
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
JobHub.Show();
}
}
I have created a SignalR Hub class as follows which has the Show() function used in the above class
using Microsoft.AspNet.SignalR.Hubs;
public class JobHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
context.Clients.All.displayStatus();
}
}
And I have the controller in which I am calling GetData() method defined in the JobInfoRepository class
public class JobInfoController : Controller
{
// GET: /JobInfo/
JobInfoRepository objRepo = new JobInfoRepository();
public IEnumerable<JobInfo> Get()
{
return objRepo.GetData();
}
}
I have created an Action named JobInfo in HomeController and returned the following view
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JobStatus</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div>
<table id="tblJobInfo" class="clientTable" style="text-align:center;margin-left:10px"></table>
</div>
</body>
</html>
#section scripts {
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="~/App/JobInfo.js"></script>
}
to retrieve the data and supply it to tblJobInfo id in the above html, a java script function is used
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../JobInfo/',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Status</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Status + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
As in the demo I found it to be working fine but when I go to http://localhost:57044/Home/JobInfo/ I get invalid data on the page besides not getting the realtime notifications as in the following image
reference to the source I found online is http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency

Related

Display Marker Using Latitude And Longitude From SQL Database With Leaflet Map In ASP.NET CORE MVC

for my website, I am using ASP.net Core MVC on Visual Studios 2019 and SQL Server Management Studio for my database.
I am trying to display markers using data(Latitude and Longitude) from my Database onto a Leaflet map. I came across a website providing a solution for this. However, it was using ASP.net instead of Asp.net Core.
Which parts of the code do I have to change for it to work on my side?
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class MapsController : Controller
{
private test2Entities db = new test2Entities();
// GET: Maps
public ActionResult Index()
{
return View(db.Maps.ToList());
}
#region [Map]
[HttpPost]
public JsonResult GetMap()
{
var data1 = Map();
return Json(data1, JsonRequestBehavior.AllowGet);
}
public IEnumerable<Map> Map()
{
return (from p in db.Maps
select new
{
Name = p.Name,
Latitude = p.Latitude,
Longitude = p.Longitude,
Location = p.Location,
Description = p.Description,
Id = p.Id
}).ToList()
.Select(res => new Map
{
Name = res.Name,
Latitude = res.Latitude,
Longitude = res.Longitude,
Location = res.Location,
Description = res.Description,
Id = res.Id
});
}
#endregion
}
}
View:
#model IEnumerable<WebApplication1.Models.Map>
#{
Layout = null;
}
<link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
<script type='text/javascript' src='http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js?2'></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<div id="map" style="height: 440px; border: 1px solid #AAA;"></div>
<script type="text/javascript">
$(document).ready(function () {
var map = L.map('map', {
center: [10.1102278, 77.8958904],
minZoom: 4,
zoom: 6
});
$.ajax({
type: "POST",
url: '/Maps/GetMap',
success: function (data) {
var result = JSON.stringify(data);
for (var i = 0; i < result.length; ++i) {
var popup ='<b>Name:</b> '+ data[i].Name +
'<br/><b>Latitude:</b> ' + data[i].Latitude +
'<br/><b>Longitude:</b> ' + data[i].Longitude+
'<br/><b>Location:</b> ' + data[i].Location;
L.marker([data[i].Latitude, data[i].Longitude])
.bindPopup(popup)
.addTo(map);
}
},
error: function (xhr) {
console.log(xhr.responseText);
alert("Error has occurred..");
}
});
L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors | Tiles Courtesy of MapQuest <img src="http://developer.mapquest.com/content/osm/mq_logo.png" width="16" height="16">',
subdomains: ['otile1', 'otile2', 'otile3', 'otile4']
}).addTo(map);
});
</script>
As far as I know, if you want to migrate from asp.net mvc to asp.net core mvc, it's easily.
You should firstly make sure you have know how to use EF core in asp.net core.
You should firstly create a model in asp.net core and create the dbcontext:
public class TestDbcontext: DbContext
{
public DbSet<Map> Documents { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
optionsBuilder.UseSqlServer(#"Your connection string");
}
}
Map class:
public class Map
{
public string Name { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string Location { get; set; }
public string Description { get; set; }
public string Id { get; set; }
}
Then you could use VS management console and type in:
add-migration initialcreate
update-database
Then add below codes in startup.cs :
services.AddDbContext<TestDbcontext>();
In MVC controller:
public class HomeController : Controller
{
private readonly ILogger _logger;
private TestDbcontext _dbContext;
public HomeController(ILogger<HomeController> logger, TestDbcontext dbContext)
{
_logger = logger;
_dbContext = dbContext;
}
public IActionResult ShowMap()
{
return View(_dbContext.Maps.ToList());
}
[HttpPost]
public IActionResult GetMap()
{
var data1 = Map();
return Json(data1);
}
public IEnumerable<Map> Map()
{
//return (from p in _dbContext.Maps
// select new
// {
// Name = p.Name,
// Latitude = p.Latitude,
// Longitude = p.Longitude,
// Location = p.Location,
// Description = p.Description,
// Id = p.Id
// }).ToList()
// .Select(res => new Map
// {
// Name = res.Name,
// Latitude = res.Latitude,
// Longitude = res.Longitude,
// Location = res.Location,
// Description = res.Description,
// Id = res.Id
// });
};
}
}
View html:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowMap</title>
</head>
<body>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin="" />
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"
integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
<div id="map" style="height: 440px; border: 1px solid #AAA;"></div>
<script type="text/javascript">
$(document).ready(function () {
var map = L.map('map', {
center: [10.1102278, 77.8958904],
minZoom: 4,
zoom: 6
});
$.ajax({
type: "POST",
url: '/Default/GetMap',
success: function (data) {
var result = JSON.stringify(data);
for (var i = 0; i < result.length; ++i) {
var popup = '<b>Name:</b> ' + data[i].Name +
'<br/><b>Latitude:</b> ' + data[i].Latitude +
'<br/><b>Longitude:</b> ' + data[i].Longitude +
'<br/><b>Location:</b> ' + data[i].Location;
L.marker([data[i].Latitude, data[i].Longitude])
.bindPopup(popup)
.addTo(map);
}
},
error: function (xhr) {
console.log(xhr.responseText);
alert("Error has occurred..");
}
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors | Tiles Courtesy of MapQuest <img src="http://developer.mapquest.com/content/osm/mq_logo.png" width="16" height="16">',
}).addTo(map);
});
</script>
</body>
</html>

How can I return javascript from a controller actionresult using ContentResult?

I'm wondering how I can return a javascript alert when the file that usually gets generated is not created in the folder. When the else statement is ran, it returns the literal text at the top of the browser tab instead of the alert that I am looking for. It looks like this:
Code:
public ActionResult DownloadFile(string path, string fileName)
{
if (System.IO.File.Exists(path))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, "application/force-download", fileName);
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('No data was found to create a CSV file!');</script>");
}
}
Firstly you can use the method public virtual ContentResult Content(string content, string contentType); rather than public virtual ContentResult Content(string content);
Controller:
public ActionResult DownloadFile()
{
return Content("alert('No data was found to create a CSV file!');", "application/javascript");
}
In addition,you can also write a result which has a Parametrical constructor and extends ContentResult.You can refer to it
Here is a demo worked:
Controller:
public ActionResult DownloadFile()
{
//return Content("alert('No data was found to create a CSV file!');", "application/javascript");
return new JavaScriptResult("alert('No data was found to create a CSV file!');");
}
public ActionResult DownloadFile1() {
return View();
}
public class JavaScriptResult : ContentResult
{
public JavaScriptResult(string script)
{
this.Content = script;
this.ContentType = "application/javascript";
}
}
DownloadFile1:
#{
ViewData["Title"] = "DownLoadFile1";
}
<h1>DownLoadFile1</h1>
<div>
<partial name="DownLoadFile" />
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$.getScript("/Test/DownloadFile");
});
</script>
}
Result:

WPF Application crashes after overriding CefApp.GetRenderProcessHandler() for JS to C# call

I am developing a wpf application by using Xilium.CefGlue and Xilium.CefGlue.WPF. My WPF application is getting crashed after implementing Xilium.CefGlue.CefApp.GetRenderProcessHandler() in SampleCefApp. Before this implementation the application was working fine without any crashes. Actually I need to call a C# function from html local page by javascript function. This functionality is working fine in 32 bit version but not in 64 bit. The following is my implementation.
internal sealed class SampleCefApp : CefApp
{
public SampleCefApp()
{
}
private CefRenderProcessHandler renderProcessHandler = new Views.DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler()
{
return renderProcessHandler;
}
}
the following message was showing for app crash
<ProblemSignatures>
<EventType>APPCRASH</EventType>
<Parameter0>StreetMap.vshost.exe</Parameter0>
<Parameter1>14.0.23107.0</Parameter1>
<Parameter2>559b788a</Parameter2>
<Parameter3>libcef.DLL</Parameter3>
<Parameter4>3.2743.1449.0</Parameter4>
<Parameter5>57bbfe66</Parameter5>
<Parameter6>80000003</Parameter6>
<Parameter7>0000000000b68267</Parameter7>
</ProblemSignatures>
Is ther any issues for libcef dll while working with 64 bit. Is anybody can help for implementing JS to C# call by using Xilium.CefGlue and Xilium.CefGlue.WPF.
The following reference code i am using for this from the link
https://groups.google.com/forum/#!topic/cefglue/EhskGZ9OndY
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System;
namespace Xilium.CefGlue.Client {
internal sealed class DemoApp: CefApp {
private CefRenderProcessHandler renderProcessHandler = new DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler() {
return renderProcessHandler;
}
}
internal class DemoRenderProcessHandler: CefRenderProcessHandler {
MyCustomCefV8Handler myCefV8Handler = new MyCustomCefV8Handler();
protected override void OnWebKitInitialized() {
base.OnWebKitInitialized();
var nativeFunction = # "nativeImplementation = function(onSuccess) {
native
function MyNativeFunction(onSuccess);
return MyNativeFunction(onSuccess);
};
";
CefRuntime.RegisterExtension("myExtension", nativeFunction, myCefV8Handler);
}
internal class MyCustomCefV8Handler: CefV8Handler {
protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue,
out string exception) {
//Debugger.Launch();
var context = CefV8Context.GetCurrentContext();
var taskRunner = CefTaskRunner.GetForCurrentThread();
var callback = arguments[0];
new Thread(() => {
//Sleep a bit: to test whether the app remains responsive
Thread.Sleep(3000);
taskRunner.PostTask(new CefCallbackTask(context, callback));
}).Start();
returnValue = CefV8Value.CreateBool(true);
exception = null;
return true;
}
}
internal class CefCallbackTask: CefTask {
private readonly CefV8Context context;
private readonly CefV8Value callback;
public CefCallbackTask(CefV8Context context, CefV8Value callback) {
this.context = context;
this.callback = callback;
}
protected override void Execute() {
var callbackArguments = CreateCallbackArguments();
callback.ExecuteFunctionWithContext(context, null, callbackArguments);
}
private CefV8Value[] CreateCallbackArguments() {
var imageInBase64EncodedString = LoadImage(# "C:\hamb.jpg");
context.Enter();
var imageV8String = CefV8Value.CreateString(imageInBase64EncodedString);
var featureV8Object = CefV8Value.CreateObject(null);
var listOfFeaturesV8Array = CefV8Value.CreateArray(1);
featureV8Object.SetValue("name", CefV8Value.CreateString("V8"), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isEnabled", CefV8Value.CreateInt(0), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isFromJSCode", CefV8Value.CreateBool(false), CefV8PropertyAttribute.None);
listOfFeaturesV8Array.SetValue(0, featureV8Object);
context.Exit();
return new [] {
listOfFeaturesV8Array,
imageV8String
};
}
private string LoadImage(string fileName) {
using(var memoryStream = new MemoryStream()) {
var image = Bitmap.FromFile(fileName);
image.Save(memoryStream, ImageFormat.Png);
byte[] imageBytes = memoryStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
}
}
The HTML file, that I loaded at the first place:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>C# and JS experiments</title>
<script src="index.js"></script>
</head>
<body>
<h1>C# and JS are best friends</h1>
<div id="features"></div>
<div id="image"></div>
</body>
</html>
The JavaScript code:
function Browser() {
}
Browser.prototype.ListAllFeatures = function(onSuccess) {
return nativeImplementation(onSuccess);
}
function App(browser) {
this.browser = browser;
}
App.prototype.Run = function() {
var beforeRun = new Date().getTime();
this.browser.ListAllFeatures(function(features, imageInBase64EncodedString) {
var feautersListString = '';
for (var i = 0; i < features.length; i++) {
var f = features[i];
feautersListString += ('<p>' + 'Name: ' + f.name + ', is enabled: ' + f.isEnabled + ', is called from js code: ' + f.isFromJSCode + '</p>');
}
feautersListString += '<p> The image: </p>';
feautersListString += '<p>' + imageInBase64EncodedString + '</p>';
document.getElementById("features").innerHTML = feautersListString;
var afterRun = new Date().getTime();
document.getElementById("image").innerHTML = '<img src="data:image/png;base64,' + imageInBase64EncodedString + '" />';
var afterLoadedImage = new Date().getTime();
console.log("ELAPSED TIME - INSIDE LIST ALL FEATURES: " + (afterRun - beforeRun));
console.log("ELAPSED TIME - IMAGE IS LOADED TO THE <img> TAG: " + (afterLoadedImage - beforeRun));
});
}
window.onload = function() {
var browser = new Browser();
var application = new App(browser);
//Lets measure
var beforeRun = new Date().getTime();
application.Run();
var afterRun = new Date().getTime();
console.log("ELAPSED TIME - INSIDE ONLOAD: " + (afterRun - beforeRun));
}
Any help is appreciated.
I enabled the cef logging. It shows the following log
[0826/171951:ERROR:proxy_service_factory.cc(128)] Cannot use V8 Proxy resolver in single process mode.
.So I changed the SingleProcess=false in CeffSetting. Now the crashing issue is solved and then the requested webpage is not showing in cefwpfbrowser.
Now I am getting the following message from the log file
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(151)] 000000001B2A7CC0: set chrome proxy config service to 000000001B234F60
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(276)] 000000001B2A7CC0: Done pushing proxy to UpdateProxyConfig
[0826/173637:VERBOSE1:webrtc_internals.cc(85)] Could not get the download directory.
How to solve the requested page not loading issue in cefwpfbrowser.

fullcalendar cannot display event

Fullcalendar is not showing the events fetched by ajax. The events is successfully passed because I can display it by pop up but it is not showing in the calendar. The fullcalendar will show events if i manually set the events but once i use the data pass from .cs file it cannot render.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web.Services;
using System.Linq;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Collections;
using System.Data;
namespace TravelPlannerO
{
public partial class Schedule : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public class Event
{
public string id { get; set; }
public string title { get; set; }
public string start { get; set; }
public string end { get; set; }
public string desc { get; set; }
public string status { get; set; }
public Event(string id, string title, string start, string end,string desc,string status)
{
this.id = id;
this.title = title;
this.start = start;
this.end = end;
this.desc = desc;
this.status = status;
}
};
[WebMethod]
public static string GetEvent()
{
string strSelect;
SqlCommand cmdSelect;
SqlDataReader dtr;
SqlConnection conn;
string connStr = ConfigurationManager.ConnectionStrings["plannerdb"].ConnectionString;
conn = new SqlConnection(connStr);
strSelect = "Select * from [Source.SavedPlan]";
cmdSelect = new SqlCommand(strSelect, conn);
conn.Open();
dtr = cmdSelect.ExecuteReader();
<script src="Scripts/moment.min.js"></script>
<script src="Scripts/jquery-ui.custom.min.js"></script>
<script src="Scripts/fullcalendar.min.js"></script>
<script type="text/javascript">
var listofevent;
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events:function (id,title,start, end, callback) {
$.ajax({
type: "POST ",
url: '<%=Microsoft.AspNet.FriendlyUrls.FriendlyUrl.Resolve(" /Schedule.aspx / GetEvent ")%>',
data: {},
contentType: "application / json;charset = utf - 8 ",
dataType: "json ",
success: function (list) {
listofevent = list.d;
alert(listofevent);
var events = [];
alert(list.d);
var obj = $.parseJSON(list.d);
console.log(obj);
$(list).find('event').each(function () {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end')
});
console.log(obj.calEvent);
});
//callback(events);
callback && callback(events);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
},
defaultDate: '2015-1-1',
selectable: true,
editable: true,
selectHelper: true,
eventLimit: true, // allow "
more " link when too many events
</script>
<link href="Content/fullcalendar.css" rel="stylesheet" /> <link href="Content/fullcalendar.print.css" rel="stylesheet" media="print" /> <link href="Content/jquery-ui.min.css" rel="stylesheet"/>
<div id='calendar'></div>
List<object> array = new List<object>();
if (dtr.HasRows)
{
var index_id = dtr.GetOrdinal("PlanId");
var index_title = dtr.GetOrdinal("Name");
var index_start = dtr.GetOrdinal("DateFrom");
var index_end = dtr.GetOrdinal("DateTo");
var index_desc = dtr.GetOrdinal("Description");
var index_status = dtr.GetOrdinal("Status");
while (dtr.Read())
{
var id = dtr.GetValue(index_id).ToString();
var title = dtr.GetValue(index_title).ToString();
var datestart = dtr.GetValue(index_start).ToString();
var dateend = dtr.GetValue(index_end).ToString();
var desc = dtr.GetValue(index_desc).ToString();
var status = dtr.GetValue(index_status).ToString();
DateTime RealStartDate = Convert.ToDateTime(datestart);
DateTime RealEndDate = Convert.ToDateTime(dateend);
string start = RealStartDate.ToString("s");
string end = RealEndDate.ToString("s");
Event eventrows = new Event(id, title, start, end,desc,status);
array.Add(eventrows);
}
}
string myJsonString = (new JavaScriptSerializer()).Serialize(array);
return myJsonString;
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
}
}
In my visual studio there are no spaces between the I think I might accidentally space it while I paste it here. I dont understand why the events is not showing. While i print 'list.d' from success: function(list), the result is
[{"id:"1","title":"testoh","start":"2015-01-01T00:00:00","end":"2015-01-02T00:00:00","desc":"abaaba","status":"first "},
[{"id:"2","title":"okok","start":"2015-05-01T00:00:00","end":"2015-05-02T00:00:00","desc":"fdgd","status":"second "}]
Is the format correct?. I noticed my callback function is not called but i dunno why
I solved this by editing the argument in the events:function (id,title,start, end, callback) to events:function (start, end,timezone, callback). btw thanks for the reply..

why these cookie codes didn't work in asp.net mvc?

I'm developing an asp.net mvc 5 online store project . I want to create cart to add Goods with Cookie . I'm confused about it and don't know why it didn't work . it didn't gave me any error . also I add break points to debug it but any data didn't send to my actions !
could anyone help me ? what's the problem ?
I'm not good in javascript and I think problem would be in javascript codes :/
Thanks in advance
Goods controller
[HttpPost]
public ActionResult AddToCart(int Id, int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product added to your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("product didn't add to your basket", MessageType.Error).Script,
Html = ""
});
}
}
public ActionResult RemoveCart(int Id)
{
try
{
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
Request.Cookies["NishtmanCart_" + Id.ToString()].Expires = DateTime.Now.AddDays(-1);
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product removed from your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
else
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("this product doesn't have in your basket", MessageType.Warning).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product didn't remove from your basket", MessageType.Error).Script,
Html = ""
});
}
}
MyJsonData.cs
public class MyJsonData
{
public string Script { get; set; }
public string Html { get; set; }
public bool Success { get; set; }
}
_GoodDetailsAjax.cshtml
#foreach (var item in Model.GoodDetails)
{
<div>
<p class="nowprice">NowPrice : #item.DetailsNowPrice</p>
<p class="preprice">PrePrice : #item.DetailsPrePrice</p>
<a class="button icon-cart" href="#" GoodID="#item.DetailsGoodID">Add to cart</a><br>
<a class="link" >Shopping Cart (0)</a>
</div>
}
#section scripts{
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
$(function () {
$("a.button.icon-cart").click(function (e) {
e.preventDefault();
var goodId = $(this).attr("GoodID");
alert(goodId); //////// I just added this code
$.ajax({
url: "/Goods/AddToCart",
data: { Id: goodId, Count: 1 },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("Error!");
}
});
});
});
</script>
}
I don't know what's the implementation of MessageBox.Show("....", MessageType.Error).Script but I'm assuming that it just generates a simple JavaScript statement like this:
Script = "alert('product added to your basket');"
So you can add this tag for the result:
<div id="CartItems">
</div>
Now it works without any problem.
All of my codes was true , I just made some simple mistakes .
I loaded a JQuery file in my layout and also I loaded another version of JQuery in my view! I deleted one of them .
And also I used those codes in a partial view and loaded they using Ajax but my partial view couldn't pass data to Controller , I moved codes to main view (GoodDetails.cshtml) and it works fine now .

Categories

Resources