Issues with binding controller methods in MVC - c#

I am implementing a page which has two navigation hyperlinks: Previous and next.
First problem, Every time I click on a hyperlink, it calls the action for the first time. Second time onwards, it stops calling the action method on the controller. I know that browser caches the link. So i used the code OutputCache... but it still does not work.
Second problem is that the action method gets called twice on one click of the hyperlink .
Could someone tell me what am I missing here? It seems pretty simple for folks who have worked in Asp.net a lot. I have put down the code I am using. Please help.
Controller code:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
public string PreviousPage(int currentPage, int blogId){
List<Blog> blogs = db.Blogs.ToList();
List<Profile> profiles = db.Profiles.ToList();
var blog = blogs.FirstOrDefault(b => b.Id == blogId);
var detailsCount = blog.BlogDetails.Count();
if (currentPage == 0)
{
ViewBag.currentPage = Session["currentPage"]= currentPage;
}
else
{
ViewBag.currentPage =Session["currentPage"]= currentPage - 1;
}
ViewBag.blogId = Session["blogId"] = blogId;
ViewBag.blogTitle = Session["blogTitle"] = blog.Title;
if (blog.BlogDetails.Any())
{
return blog.BlogDetails[ViewBag.currentPage].BlogPage;
}
else {
return " ";
}
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
public string NextPage(int currentPage, int blogId){
List<Blog> blogs = db.Blogs.ToList();
List<Profile> profiles = db.Profiles.ToList();
var blog = blogs.FirstOrDefault(b => b.Id == blogId);
var detailsCount = blog.BlogDetails.Count();
if (currentPage == detailsCount - 1)
{
ViewBag.currentPage = Session["currentPage"] = currentPage;
}
else
{
ViewBag.currentPage = Session["currentPage"] = currentPage + 1;
}
ViewBag.blogId = blogId;
Session["blogTitle"] = blog.Title;
if (blog.BlogDetails.Any())
{
return blog.BlogDetails[ViewBag.currentPage].BlogPage;
}
else
{
return " ";
}
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult UpdateTitleServer(){
var title = Session["blogTitle"];
int blogId = (int)Session["blogId"];
var currentPage = (int)Session["currentPage"];
var result = new {
Title = title.ToString(),
BlogPrevLink = string.Format("/BloggerHome/PreviousPage?currentPage={0}&blogId={1}",currentPage,blogId),
BlogNextLink = string.Format("/BloggerHome/NextPage?currentPage={0}&blogId={1}",currentPage,blogId)
};
return Json(result,JsonRequestBehavior.AllowGet);
}
View code:
#Ajax.ActionLink("<----", "PreviousPage","BloggerHome", new { currentPage = ViewBag.currentPage, blogId = ViewBag.blogId }, new AjaxOptions() {HttpMethod="Post", OnComplete="UpdateTitleClient", UpdateTargetId = "contentPanel" }, new {Id="PrevPage"})
#Ajax.ActionLink("---->", "NextPage","BloggerHome", new { currentPage = ViewBag.currentPage, blogId = ViewBag.blogId }, new AjaxOptions() {HttpMethod="Post",OnComplete="UpdateTitleClient",UpdateTargetId="contentPanel" },new {Id="NextPage"});
JavaScript method:
function UpdateTitleClient() {
$.getJSON("BloggerHome/UpdateTitleServer", function (data) {
$("#blogTitle").html(data.Title);
$("#PrevPage").attr("href", data.BlogPrevLink);
$("#NextPage").attr("href", data.BlogNextLink);
});
}

Remember that getJSON() is an async method so the sequence of events may not be very predictable if you are stepping through the code using a debugger.
getJSON() doesnt have a async:false setting so just use ajax instead set async to false and dataType to json. Something like below:
$.ajax({
dataType: "json",
url: yoururl,
async: false,
data: data,
success: function (data) {
$("#blogTitle").html(data.Title);
$("#PrevPage").attr("href", data.BlogPrevLink);
$("#NextPage").attr("href", data.BlogNextLink);
}
});

The line #Scripts.Render("~/bundles/jqueryval") , Jquery validation script inclusion is causing the controller methods to call twice. I am not sure why this is causing the problem .Once this line was removed, it calls the controller method once only.
This is how my script header looked like before
<head>
<meta charset="utf-8" />
<title>Test</title>
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="~/Scripts/jquery-1.8.2.min.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.8.24.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
**#Scripts.Render("~/bundles/jqueryval") // Removed this line**
</head>

This issue is due to jquery references being added twice.
First reference was :
**<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"</script>**
Second Reference was due to the line :
#Scripts.Render("~/bundles/jqueryval")
The above line adds three scripts to the web page
**<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>**
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
The two highlighted script tags are duplicates which caused the controller methods to be called twice . I removed one of them and it works fine now.

Related

Pass a JS value to a model without reloading a View

Is it possible to pass a JavaScript value as a parameter to a Model without reloading the page? My goal is to change a dropdown based on what the user selected in an earlier dropdown. I tried:
<script>
$(function () {
$(document).on('change', '#selectUserNames', function () {
var selectedVal = $(this).val();
var userClaims = #Html.Raw(Json.Serialize(Model.GetUserClaims(selectedVal))); //////////PASSING VALUE HERE
if (selectedVal == 'ABC#GMAIL.COM') {
var html = '<option selected disabled>Select Claim:</option>';
for (var i = 1; i < userClaims.length; ++i) {
html = html + '<option>' + userClaims[i] + '</option>';
}
$('#selectAuthPolicy').html(html);
}
})
})
</script>
I also thought this might be useful, but I am trying not to reload the view (which I believe this will do)

jQueryu ui autocomplete doesn´t show anything in MVC c#

I want to display an autocomplete textbox in a MVC C# View using jQuery-ui autocomplete, this is the code of my view
#{
ViewBag.Title = "Index";
}
<script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Borrar/autocompletar",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#SearchString").val(ui.item.value);
}
}
});
});
</script>
<div class="container col-md-10 col-md-offset-3">
<h2>Autocompletar</h2>
#using (Html.BeginForm())
{
<p>
Empresa: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
</div>
this is the code of the controller that should populate the textbox
public JsonResult autocompletar(string prefix)
{
List<GFC_Site.ViewModels.EmpresaAutocomplete> listado = new List<GFC_Site.ViewModels.EmpresaAutocomplete>();
ProxyGFC.ServiceGFCClient cliente = new ProxyGFC.ServiceGFCClient();
List<WcfService.Entidades.EmpresaAutocomplete> listadoBase = new List<WcfService.Entidades.EmpresaAutocomplete>();
listadoBase = cliente.Autocompletar(prefix);
foreach (var item in listadoBase)
{
GFC_Site.ViewModels.EmpresaAutocomplete dato = new ViewModels.EmpresaAutocomplete();
dato.empresa = item.empresa;
//dato.np = item.np;
listado.Add(dato);
}
return Json(listado, JsonRequestBehavior.AllowGet);
}
where (GFC_Site.ViewModels.EmpresaAutocomplete) is a class with only one string property (empresa) and (ProxyGFC.ServiceGFCClient cliente) is a connection to a WCF Server, the WCF is the one that connects the application with the database and (List listadoBase) is a class in WCF with two properties(empresa and np).
and this is the method in WCF that retrieve the info that I want to display in the textbox
public List<EmpresaAutocomplete> Autocompletar(string prefix)
{
OdbcCommand cmd = Helper.Commandos.CrearComando();
cmd.CommandText = "select numero_patronal, nombre_empresa from empresas where estado= ? and nombre_empresa like ?";
cmd.Parameters.Add("#estado", OdbcType.VarChar).Value = "1";
cmd.Parameters.AddWithValue("#empresa", prefix + "%");
List<EmpresaAutocomplete> data = new List<EmpresaAutocomplete>();
try
{
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
EmpresaAutocomplete datos = new EmpresaAutocomplete();
datos.np = reader["numero_patronal"].ToString();
datos.empresa = reader["nombre_empresa"].ToString();
data.Add(datos);
}
}
catch (Exception ex)
{
throw new ApplicationException("Excepcion :", ex);
}
return data;
}
well, my problem is that the textbox doesn´t show anything, actually it gets frozen
could you please tell me what seems for you to be the problem?
First off, let’s take take a look at autocomplete in action, starting with a text input:
<label for=”somevalue”>Some value:</label><input type=”text” id=”somevalue” name=”somevalue”/>
If we add a reference to the jQuery UI script file and css file, we can add a script block to our view:
<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {
$(‘#somevalue’).autocomplete({
source: ‘#Url.Action(“Autocomplete”)’
});
}) </script>
This script block identifies the text input by id and then invokes the autocomplete function to wire up the autocomplete behaviour for this DOM element. We pass a URL to identify the source of the data. For this post I’ve simply created an ASP.NET MVC action that returns JSON data (shown below). Note that in the view I used Url.Action to look up the URL for this action in the routing table – avoid the temptation to hard-code the URL as this duplicates the routing table and makes it hard to change your routing later.
public ActionResult Autocomplete(string term)
{
var items = new[] {“Apple”, “Pear”, “Banana”, “Pineapple”, “Peach”};
var filteredItems = items.Where(
item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
);
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}
https://blogs.msdn.microsoft.com/stuartleeks/2012/04/23/asp-net-mvc-jquery-ui-autocomplete/

How to Implement Autocomplete Textbox in MVC

I am facing a problem in autocompleting the textbox vith hardcoded data, my json "Search" method does not fire i have been search a lot of code implement it into my project but did not get any success yet. i dont know where is the problem. kindly help me thankx in advance
Model:
public class Locations
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller:
public JsonResult Search(string query)
{
List<Locations> locations = new List<Locations>()
{
new Locations() {Id = 1, Name = "London"},
new Locations() {Id = 2, Name = "Walles"},
new Locations() {Id = 3, Name = "Birmingham"},
new Locations() {Id = 4, Name = "Edinburgh"},
new Locations() {Id = 5, Name = "Glasgow"},
new Locations() {Id = 6, Name = "Liverpool"},
new Locations() {Id = 7, Name = "Bristol"},
new Locations() {Id = 8, Name = "Manchester"},
new Locations() {Id = 9, Name = "NewCastle"},
new Locations() {Id = 10, Name = "Leeds"},
new Locations() {Id = 11, Name = "Sheffield"},
new Locations() {Id = 12, Name = "Nottingham"},
new Locations() {Id = 13, Name = "Cardif"},
new Locations() {Id = 14, Name = "Cambridge"},
new Locations() {Id = 15, Name = "Bradford"},
new Locations() {Id = 16, Name = "Kingston Upon Hall"},
new Locations() {Id = 17, Name = "Norwich"},
new Locations() {Id = 18, Name = "Conventory"}
};
List<string> Loc;
Loc = locations.Where(x => x.Name.StartsWith(query.ToLower())).Select(x => x.Name).ToList();
return Json(Loc, JsonRequestBehavior.AllowGet);
}
View:
#model IEnumerable<SearchBox.Models.Locations>
#using SearchBox.Models
#{
ViewBag.Title = "Index";
}
<link href="~/Content/Autocomplete/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Autocomplete/jquery-ui.js"></script>
<link href="~/Content/Autocomplete/jquery-ui.theme.css" rel="stylesheet" />
<script type="text/javascript">
$("#tags").autocomplete({
source: '#Url.Action("Search")'
});
</script>
<input type="text" id="tags" />
You need to make ajax request instead of passing just url in data source.
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/jquery-1.12.4.js"></script>
<script src="~/Content/jquery-ui.js"></script>
<input type="text" id="tags" />
<script type="text/javascript">
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("Search")',
dataType: "jsonp",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
}
});
</script>
See how to use autocomplete with ajax request.
I have implemented this in my project. Please check if you can make use of it
<div class="tag_cover" style="margin-top:60px; margin-left:57px">
<input type="text" style="width:300px; display:inline-block; border:transparent" class="tag_input brzero has-icon" id="SkillSet" list="json-datalist" placeholder="Employee name or Skills">
<datalist id="json-datalist"></datalist>
</div>
JQuery:
$(".tag_input").keyup(function (e) {
var type = $("input[name='search']:checked").val();
if (type == "Name") {
var sString = $("#SkillSet").val();
if (sString == null || sString == "") {
e.preventDefault();
}
else {
$.ajax({
url: "#Url.Action("GetEmployeeNameByKeyword","Home")",
type: "POST",
data: { 'SearchedString': sString },
dataType: "json",
success: function (data) {
if (data == null || data == "") {
//alert("no skills found");
}
else {
var dataList = document.getElementById('json-datalist');
$(dataList).empty();
$.each(data, function (key, value) {
$(dataList).append($('<option>').text(value.UserNames.trim()).attr("value", value.UserId));
});
}
},
error: function () {
alert("failure");
}
});
}
}
}
Controller:
public JsonResult GetEmployeeNameByKeyword(string SearchedString)
{
List<UserProfile> EmployeeNames = new List<UserProfile>();
EmployeeNames = _db.UserProfiles.Where(i => i.UserNames.Contains(SearchedString)).ToList();
return Json(EmployeeNames, JsonRequestBehavior.AllowGet);
}
I have been looking everywhere for references on a feature like this, myself.
I don't have enough rep to comment, but Naveen's answer worked for me after I started going one line at a time with console.log("PASS");. If the function is never called on an event like keyup, then it likely means one of the variable names is wrong or there is bad syntax. The reason you could not get any calls to the javascript was because of a missing }); which is an ending statement for JQuery functions. The end of the code for the scripting part should appear like so:
}
}); //END $.ajax
}
}
}); //END keyup function
Using Razor, with T4MVC at an MVC5 project, we'll implement jQuery Autocomplete.
You should have inside your solution, one or more projects, and inside your project, among many other usual MVC5 things, the folders Models, Views and Controllers. And inside of them...
NuGet
Get the dependencies in place (your should know how to get them using Visual Studio):
jQuery: https://www.nuget.org/packages/jQuery/3.6.0
jQuery-UI: https://www.nuget.org/packages/jQuery.UI/
Then put them in the BundleConfig.cs files, at the App_Start folder:
using System.Web.Optimization;
namespace MyProject.Web
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles
.Add(new ScriptBundle("~/bundles/jquery")
.Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui.js",
));
bundles
.Add(new StyleBundle("~/Content/css")
.Include(
"~/Content/jquery-ui.css"
));
}
}
}
This will add the dependencies you´ll need to the view (see View section down below for more instructions).
Model
namespace MyProject.Web.Models.MyModelFolder
{
public class MyModel
{
public string MyValue { get; set; }
public string MyAnotherValue { get; set; }
public string AndAnotherValue { get; set; }
}
}
View
(Using Bootstrap)
#model MyProject.Web.Models.MyModelFolder.MyModel
<div class="ui-widget">
#Html.LabelFor(model => model.MyValue)
#Html.EditorFor(model => model.MyValue, new { htmlAttributes = new { #class = "form-control", id = "myTextbox" } })
#Html.ValidationMessageFor(model => model.MyValue, "", new { #class = "text-danger" })
</div>
We'll be querying the MyValue field.
And add the dependencies from the BundleConfig.cs where you'll need them in your page:
<header>
#Styles.Render("~/Content/css")
</header>
<body>
<p>Your Content</p>
#Scripts.Render("~/bundles/jquery")
</body>
Adding the Autocomplete
There are two ways you can accomplish this, as:
Internal file to the page or,
as an external .js file.
NOTE: Autocomplete must be always below the required jQuery dependencies.
Internal file
In the .cshtml file. Inside your <body> tag, at the bottom of it:
<script>
$("#myTextbox").autocomplete({
source: '#Url.Action(MVC.MyController.MyMethod())'
});
</script>
Or instead in the...(Choose one, not both!)
External file
In the Scripts folder. Remember to add this block at the bottom of your view to call the function from the outside.
#section Scripts {
<script src="~/Scripts/autocomplete.js"></script>
}
And in the Scripts folder in a JS file add:
$(document).ready(function () {
$("#myTextbox").autocomplete({
source: '/MyController/MyMethod',
});
})
You can see there the method you'll be calling from from the controller.
Controller
#region jQuery Method Calls
using MyProject.Web.Models.MyModelFolder;
public virtual JsonResult MyMethod(string term)
{
// _myViewModel is a partial model
List<MyModel> MyAutocompleteList = new List<MyModel>();
/* In this example I´m using AutoMapper, and getting back the List
from the Database (layer, using Entity Framework), using Repository
Pattern (layer) and Unit of Work Pattern. */
// But you can get the List however way you want.
MyAutocompleteList = _theMapper.GetMyModelList(_operationsLayerService.GetMyModelList());
// This LINQ query makes the magic happen
var result = from U in MyAutocompleteList
where U.MyValue.Contains(term)
// It retrieves a composed string, not just a single value.
select new { value = $"{U.MyValue} | {U.MyAnotherValue} {U.AndAnotherValue}" };
// Security vulnerabilities? https://stackoverflow.com/a/21453075/7389293
return Json(result, JsonRequestBehavior.AllowGet);
}
#endregion
That's it.

asp.net mvc partial view is caching my model values

I am working on an asp.net mvc web application. and i have a WebGrid, where i added a Page-size drop-down list to enable users to select how many records they like to have per page.
the Action method is:-
[OutputCache(CacheProfile = "NoCache")]
public ActionResult Disposed(string filter = null, int page = 1, int? pageSize = null, string sort = "Technology.Tag", string sortdir = "ASC")
{
GridList<DisposedResources> gridrecords = repository.GetDisposedResourcesForGrid(filter, page, pageSize, sort, sortdir, "rack");
ViewBag.PagedSizeOptions = new PageOptions().FilterOptions;
if (Request.IsAjaxRequest())
{
return PartialView("_disposed", gridrecords);
}
return View("Disposed", gridrecords);
}
and here is the repository method :-
public GridList<DisposedResources> GetDisposedResourcesForGrid(string filter, int page, int? pageSize, string sort, string sortdir, string resourcetype)
{
if (!pageSize.HasValue)
{
pageSize = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]);
}
var records = new GridList<DisposedResources>();
records.currentfilter = filter;
records.TotalRecords = GetDisposedResourcesForGridCount(filter, resourcetype);
records.hasNetworkInfo = false;
records.hasSystemInfo = false;
records.CurrentPage = page;
records.PageSize = pageSize.Value;
records.currentsort = sort;
records.currentsortdir = sortdir;
records.Content = tms.DisposedResources.Include(a=>a.Technology).Where(x => (filter == null ||
(x.Technology.Tag.ToLower().StartsWith(filter.ToLower()))
) && x.ResourceType.ToLower() == resourcetype.ToLower())
.OrderBy(sort + " " + sortdir)
.Skip((page - 1) * pageSize.Value)
.Take(pageSize.Value).ToList();
return records;
}
the Disposed view is :-
#model S.ViewModels.GridList<S.Models.DisposedResources>
Show #Html.DropDownList("FilterSize", new SelectList(ViewBag.PagedSizeOptions, "Value", "Text", ViewBag.pagesize ), new { #id= "FilterSize1",#class="SmallDropDown3"}) <span class="hidden-phone">per page.</span>
<div id="disposed">
#Html.Partial( "_disposed",Model)
</div>
#section Scripts {
<script type="text/javascript">
$("body").on('change', '#FilterSize1', function () {
//$(SizeProgressSort).show();
$.ajaxSetup({ cache: false });
$.ajax({
type: "Get",
url: '#Url.Action("Disposed")',
data: { pageSize: $('#FilterSize1').val(), page: "1", sort: $('#currentsort').val(), sortdir: $('#currentsortdir').val() },
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$('#disposed').html(data);
}
function errorFunc() {
alert('error');
}
});
</script>
}
and the _disposed partial view is:-
#model S.ViewModels.GridList<S.Models.DisposedResources>
var gridcolumns = new List<WebGridColumn>();
gridcolumns.Add(new WebGridColumn()
{
ColumnName = "Technology.Tag",
Header = Html.DisplayNameFor(model => model.Content.FirstOrDefault().Technology.Tag).ToString(),
CanSort = true
});
//code goes here...
var grid = new WebGrid(
canPage: true,
rowsPerPage: Model.PageSize,
canSort: true,
ajaxUpdateContainerId: "grid");
grid.Bind(Model.Content, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(htmlAttributes: new { id = "grid" }, // id for ajaxUpdateContainerId parameter
fillEmptyRows: false,
tableStyle: "table table-bordered table-hover",
mode: WebGridPagerModes.All,
columns: gridcolumns
);
}
</div></div></div>
<input type="hidden" value="#Model.currentsort" id="currentsort" /> #Model.currentsort
<input type="hidden" value="#Model.currentsortdir" id="currentsortdir" /> #Model.currentsortdir
the problem i am facing is that the two parameters; currentsort + currentsortdir which are being passed as part of the javascript will not be changed,and the user will loose the current sort order if he chose to chnage the page size drop down-list. so can anyone advice what is the problem, now even if i chose to display the two values:-
Model.currentsort
&
Model.currentsortdir
they will always have the defualt value, although these values are being changed inside the repository method... but seems the partial view is somehow caching the old values for these two parameter ?
The ModelState is probably overriding the values you changed in your model. Call ModelState.Clear() in your action method and you should see the changed values.
I know that you have done the cache setting through ajaxSetup but try putting cache:false inside your script and see if that makes a difference.
$.ajax({
cache: false
type: "Get",
url: '#Url.Action("Disposed")',
--------

fullCalendar events not showing even though correct JSON feed

As a bunch of others I have a problem getting my JSON feed events to render in the calendar. The problem is often wrong JSON formating, but this is not the case since I've validated it with JSONlint and hardcoded the JSON feed in Site.Master with positive result.
FireBug is getting the JSON response correctly but it is still not showing up in fullCalendar. I'm out of ideas.
The FireBug response:
[{"id":1,"title":"TESTTITLE","info":"INFOINFOINFO","start":"2012-08-20T12:00:00","end":"2012-08-20T12:00:00","user":1}]
JSON.aspx
public partial class JSON : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get events from db and add to list.
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
Response.Write(json);
Response.End();
}
}
Site.master
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href='fullcalendar/fullcalendar.css' rel='stylesheet' type='text/css' />
<script src='jquery/jquery-1.7.1.min.js' type='text/javascript'></script>
<script src='fullcalendar/fullcalendar.js' type='text/javascript' ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: 'JSON.aspx'
})
});
</script>
I've been scanning related questions for days but none of them seems to fix mine...
Try this , you have to have a webmethod in aspx file that fullcalendar can call asynchronously
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: function (start, end, callback) {
$.ajax({
type: "POST", //WebMethods will not allow GET
url: "json.aspx/GetEvents", //url of a webmethod - example below
data: "{'userID':'" + $('#<%= hidUserID.ClientID %>').val() + "'}", //this is what I use to pass who's calendar it is
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = $.parseJSON(doc.d); //.net returns json wrapped in "d"
$(obj.event).each(function () { //yours is obj.calevent
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
callback(events);
}
});
}
})
then this would be in json.aspx
[WebMethod(EnableSession = true)]
public static string GetEvents(string userID)
{
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
return json;
}

Categories