Context:
Hello, I'm developing an on line application of Tennis Club Management... I would like to create an "Available Tennis Court Interface" that allows the user to check if a court is busy or free... So in my Interface I have one DatePicker, an image "Google Maps" of the Tennis Club and 13 labels that represents all tennis courts. So in this interface, if a tennis court is busy, I would like to "color" the label in red and if the tennis court is free, in green...
Here my Interface:
Code
For that, I'm using Jquery, JavaScript and Json... Here what I have tried to make in my View :
<script type="text/javascript">
function loadCourts() {
var maDate = $('#datePicker').val();
$.post({
type: 'POST',
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
data: "{ 'date' : " + maDate + " }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
alert('test');
//How to use data and verify if a tennis is free or not ?
},
error: function(x, t, m) {
if (t === "timeout") {
window.HandleTimeout();
} else {
alert(t);
}
}
});
}
</script>
<h2>Emplacement(s) disponible(s)</h2>
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(chargerCourts());
});
</script>
//Here the label
<div class="AvailableCourt">
<div class="label1" align="center">
#Html.Label("1")
</div>
<div class="label2" align="center">
#Html.Label("2")
</div>
<div class="label2" align="center">
#Html.Label("3")
</div>
<div class="label2" align="center">
#Html.Label("4")
</div>
<div class="label3" align="center">
#Html.Label("5")
</div>
<div class="label4" align="center">
#Html.Label("6")
</div>
<div class="label5" align="center">
#Html.Label("7")
</div>
<div class="label6" align="center">
#Html.Label("8")
</div>
<div class="label7" align="center">
#Html.Label("9")
</div>
<div class="label8" align="center">
#Html.Label("10")
</div>
<div class="label9" align="center">
#Html.Label("11")
</div>
<div class="label10" align="center">
#Html.Label("12")
</div>
<div class="label11" align="center">
#Html.Label("13")
</div>
}
</div>
Controller method
//Get all the tennis courts and verify if a court is busy or not (Available attribute)
public JsonResult GetTennisCourt(DateTime date)
{
System.Diagnostics.Debug.WriteLine("test");
var reservations = db.Reservations.Include(c => c.Customer);
foreach (var reservation in reservations)
{
//Verify that a court is available or not
if (reservation.Date ==date)
{
if (date.Hour > reservation.FinishTime.Hour || date.Hour < reservation.StartTime.Hour)
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(t => t.ID == id);
tennisCourt.Available = true;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
}
else
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(s => s.ID == id);
tennisCourt.Available = false;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
break;
}
}
}
var courts = from c in db.TennisCourts
select c;
courts = courts.OrderBy(c => c.ID);
System.Diagnostics.Debug.WriteLine("test");
return Json(courts, JsonRequestBehavior.AllowGet );
}
When I'm using Firebug, I get an error in my function "loadCourts" and so my controller's method (getTennisCourts) is never reaches) I don't understand why:
Questions
So, my questions are :
1) Why get I an error in Firebug ?
2) Why is my Controller's method never reaches ?
3) How could I use "data" in my function "loadCourts" to check if a tennis court is free or not ?
Sorry for the length and thanks in advance...
For Darin Dimitrov :
Try like this:
// get the underlying Date object from the datepicker instead
// of using .val()
var maDate = $('#datePicker').datepicker('getDate');
$.ajax({
type: 'POST',
url: '#Url.Action("GetTennisCourt", "AvailableCourt")',
data: '{ "date":"\\/Date(' + maDate.getTime() + ')\\/" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
// we loop through the collection of courts
// returned by the server and we can access each
// element's properties
$.each(data, function(index, court) {
alert(court.ID);
});
},
error: function(x, t, m) {
if (t === 'timeout') {
window.HandleTimeout();
} else {
alert(t);
}
}
});
Notice that I used $.ajax instead of $.post. And I have used the datepicker's getDate method to fetch the native Date object and encode it.
I dont know C# but this line:
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
Is resolving the url as an object, if you had
url : '/path/to/controller'
It might work
The 'data' in the success function is JSON so you can treat it as an object.
data.xyz
Related
I want to click "2" Ajax will call ActionResult and put new question up but not rerun page
i have been trying two day but it haven't worked
People help me, please
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return View(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Json",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
In HTML:
<li>
1
</li>
enter image description here
Thanks for reading
I changed but it dont work!!
I learned it myself so it was hard to get started
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return PartialView(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Html",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#baitetstiq').html(a);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
Full HTML:
<div class="col-md-9" style="border-top-style:double;
border-top-color:aquamarine;
border-top-width:5px; margin-left:-15px">
<p style="text-align:center">
<b>Thời Gian Còn Lại Là:xxx</b>
</p>
<div id="baitestiq"></div>
#foreach(var item in Model)
{
<div class="baitest">
<div class="ques">
<img src="~/Hinh_Cauhoi/#item.Cauhoi" />
</div>
<div class="anw">
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn1" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn2" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn3" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn4" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn5" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn6" />
</div>
</div>
<div class="numbertest">
<ul>
<li>
1
</li>
</ul>
</div>
1st you need to return a partial view.
2nd you need to make a get ajax request and not a post
3rd you need to test first the result of #Url.Action("BaiTestIQ","TestIQ"), translate this to a URL, directly to make sure it returns the expected results without the ajax call to avoid getting into sideways with routing etc. see this for example
See a working example here
Update:
I see it now, you changed dataType: "Html"
You need to change several things:
1. The method is not changing any state so it should not be declared as a post method. You need to remove [HttpPost] attribute.
You need to be aware of ajax parameters contentType and dataType. From the documentation: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8'). This specifies what type of data you're sending to the server. And dataType (default: Intelligent Guess (XML, json, script, or HTML)) specifies what jQuery should expect to be returned. In your case, it should be 'json' because you are using the result return from a LINQ query.
So the method might look like:
public JsonResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return Json(cauhoi.ToList(), JsonRequestBehavior.AllowGet);
}
3. Moving to the ajax call:
<script>
function loadcauhoi(num) {
$.ajax({
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
type: "GET",
cache: false,
dataType: "json",
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
**But I'd like to suggest another approach using a ViewModel with a partial view because serializing JSON data can sometimes get you errors. A quick tutorial
I will show you all the moving parts involved.
View:
#{
ViewBag.Title = "Partners";
}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h1>Partners</h1>
<p>Click to see survey answers or delete partner</p>
<table class="table">
<thead>
<tr>
<th>Partner Name</th><th>Actions</th>
</tr>
</thead>
<tbody>
#foreach ( var NameIdPair in ViewBag.PartnersAndIds )
{
<tr>
<td>
#NameIdPair.Name
</td>
<td>
<button class="btn btn-info view-partner-surveys" data-partnerid="#NameIdPair.Id">View Survey Answers</button>
<button class="btn btn-warning delete-partner" data-partnerid="#NameIdPair.Id">Delete Partner</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#section bottommost {
<script type="text/javascript">
$('.delete-partner').click(function () {
var row = $(this).closest('tr');
$.ajax({
method: 'POST',
url: 'DeletePartner',
data: { pid: $(this).attr('data-partnerid') },
dataType: 'json',
processData: false,
beforeSend: function () {
row.addClass('processing');
},
success: function (retinfo) {
if (retinfo.DeletedSuccessfully) { row.remove(); }
else { alert("Error .."); row.removeClass('processing'); }
},
error: function () { alert("Error"); row.removeClass('processing'); }
});
});
</script>
}
The problem is occuring with the AJAX call invoked with $('.delete-partner').click. The controller handling the request is the simple
[HttpPost]
public ActionResult DeletePartner ( int pid )
{
return Json(new { DeletedSuccessfully = this._Db.DeletePartner(pid) });
}
which used the method DeletePartner in a model defined by
public bool DeletePartner ( int id )
{
SqlCommand cmd = new SqlCommand("DeletePartner", this._Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
this._Conn.Open();
bool succeeded = cmd.ExecuteNonQuery() == 1 ? true : false;
this._Conn.Close();
return succeeded;
}
The sproc its calling is the simple
CREATE PROCEDURE DeletePartner
#id INT
AS
DELETE FROM Partners WHERE id=#id
Any idea where I'm going wrong here?
You should use the url of your ajax call like following.
url: '#Url.Action("DeletePartner")'
You have to give ajax url in the format like
url : '../controllerName/ActionName'
[HttpPost]
public ActionResult DeletePartner ( int pid )
{
return Json(new { DeletedSuccessfully = this._Db.DeletePartner(pid) });
}
The DeletedSuccessfully variable is not recognised by the controller. So it may cause 500 error
i want to save canvas image to folder and share that in facebook on wall of the user logged i'm using html2canvas plugin but my issue is the div element is not getting drawn in the canvas the data in the div is coming from database following is the code i have written.
HtmlCode:
<div class="fan_wrap">
<ul class="fan_list">
<% foreach (ProfileDetails currentFollowers in AllFollowers)
{
%>
<li <%if (currentFollowers.ID != 0) { Response.Write("class=\"locate\""); } %>>
<img src="<%=currentFollowers.ProfileImg %>" alt="<%=currentFollowers.Name %>" title="<%=currentFollowers.Name %>" />
<div class="frame"></div>
</li>
<%} %>
</ul>
<div class="clearfix"></div>
<div class="logo_water_mark">
<img src="images/trans_logo.png" alt="" />
</div>
</div>
Javascript Code:
$(document).ready(function () {
$('#share_lnk').on('click',function () {
html2canvas($('.fan_wrap'), {
onrendered: function (canvas) {
var image = canvas.toDataURL("image/jpeg");
var url = canvas.toDataURL("image/jpeg");
image = image.replace('data:image/jpeg;base64,', '');
$.ajax({
type: 'POST',
url: 'FacebookLogin.aspx/UploadImage',
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
});
});
});
First thing is that you have to save the canvas image on the domain from where you want to share it as your facebook app supports only one. next you can share the url of the pic to be sharer like below:
FB.ui({
method: 'feed',
name: "some name",
link: "somelink.com",
picture: urltobeshared,
caption: 'some caption',
description: "some descrtiption",
},
function(response) {
if (response && response.post_id) {
console.log('Thank you');
}
}
);
},
docs are here.Hope that helps
I have a question on how to achieve the following:
I have a dropdownlist with activities and I want on the onchange event of an activity, that my list would be fetched with the id that is set in my model with ajax
example of my code is as following
Ajax Method to set The ID
function GetSelectedValue(DropDownID, HiddenFieldID) {
$('#' + HiddenFieldID).val($('#' + DropDownID + ' option:selected').val());
$('#' + DropDownID).change(function () {
$('#' + HiddenFieldID).val($('#' + DropDownID + ' option:selected').val());
$.ajax({
url: 'Afmeldingen',
type: "POST",
data: JSON.stringify({ 'ActiviteitenID': $('#' + DropDownID + ' option:selected').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
jQuery.globalEval(data.Callback);
},
error: function (error) {
//alert(error);
}
});
});
}
$(document).bind('pageinit', function () {
GetSelectedValue('details', 'act_id');
});
The Form element
#using (Html.BeginForm())
{
<div data-role="collapsible" data-inline="true" data-content-theme="b" data-collapsed="false">
<h3>#DateTime.Today.ToShortDateString()</h3>
<div data-role="collapsible-set" data-inline="true" data-content-theme="b" data-collapsed="true">
<select id="details">
#foreach (var item in Models.Taken.ActivityList)
{
<option value="#item.ID">#item.Comments</option>
}
</select>
#Html.Hidden("act_id")
#foreach (var item in Talent.Subscription.Fetch(null, Models.Taken.ActID ?? 1L, null, null))
{
<div data-role="collapsible" data-content-theme="b" data-collapsed="true">
<h3>
#Html.Label("", item.Participant.CompleteName)
</h3>
#Html.CheckBoxFor(m => m.DeelnemerActive.HasValue, htmlAttributes: new { data_role = "CheckBox" })
#foreach (var af in Talent.Afmelding.Fetch(null, Models.Tasks.ActID ?? 1L, null, null))
{
#Html.Label("", "Comments")
#Html.TextBox("Reason", af.Reason);
}
</div>
}
</div>
</div>
}
I hope you can help me to achieve this, or that you have an idea how to do this
This is probably the best example I can find that would help you.
http://blog.krisvandermast.com/CommentView,guid,b1a264ac-c48f-463e-9f55-db24e2a9b635.aspx
He loads data from a partial view dynamically on the onclick of a
button. You could use your onchange here.
-
Have a look at this example to see how cascading dropdowns work:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/cascading-dropdownlist-in-Asp-Net-mvc/
-
You could also consider using knockout js, like described here:
http://www.dotnetexpertguide.com/2012/06/cascading-dropdown-knockoutjs-aspnet.html
Apologies if this i trivial, i have read many other comments and still cannot see what is wrong. I have done a few tutorials and they seem to work ok, so I am really missing something simple.
I have a basic 'remove' link that i want to do a JQuery Post back to the controller to remove an item from the database and then update the view.
My View / Javascript:
<script type="text/javascript">
$(function () {
$(".RemoveLink").click(function () {
var id = $(this).attr("data-id");
if (id != '') {
$.post("#Url.Content("~/Agent/Remove")", { "id": id }, function (data) { alert('Here i am'); });
}
});
});
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.ID" >Remove</a>
</td>
</tr>
}
My Controller:
[HttpPost]
public ActionResult Remove(int id)
{
return Json(new { Data = "true" });
}
Any assistance will be great.
Use #Url.Action("Remove", "Agent") instead.
#Url.Content("...") is used to locate any static content of the site.
Cheers
Below code works well.
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<input type="button" class="RemoveLink" id="#item.ID" Value="Remove" />
</td>
</tr>
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('.RemoveLink').live("click", function () {
Remove($(this));
});
});
function Remove(_this) {
var Id= $(_this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("Remove", "Agent")',
data: "{id: '" + Id + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
//do something here......
},
error: function () {
}
});
}
</script>