Can not pass ViewBag property to jQuery method - c#

I'm having a problem trying to get a ViewBage property value and pass it into a jQuery method.
For example, in my code below, #ViewBag.CountResult have the value 1, and it is displayed in my browser, but when passed into the updateResultFooter method, it is like "" ! Don't get why. Down is my view. Any help ?
Thanks in advance
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
<script type="text/javascript">
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
$(document).ready(function (){
updateResultFooter("#ViewBag.CountResult", "#ViewBag.PageNumber", "#ViewBag.PageCount");
$("#idBnSearch").click(function (){
var telValue = $("#idTxTel").val();
pageIndex = 0;
doReverseSearch(telValue, pageIndex, methodUrl);
updateResultFooter("#ViewBag.CountResult", 0, "#ViewBag.PageCount");
});
$("#bnNextPage").live("click", function (){
var telValue = $("#idTxTel").val();
pageIndex = pageIndex + 1;
doReverseSearch(telValue, pageIndex, methodUrl);
updateResultFooter("#ViewBag.CountResult", pageIndex, "#ViewBag.PageCount");
});
});
function updateResultFooter(resultCount, pageIndex, pageCount){
if (resultCount == '0')
$("#resultFooter").hide();
else
{
$("#resultFooter").show();
if (pageIndex == 0)
$("bnPreviousPage").attr('disabled', 'disabled');
else
$("bnPreviousPage").removeAttr('disabled');
if ((pageIndex + 1) == pageCount)
$("bnNextPage").attr('disabled', 'disabled');
else
$("bnNextPage").removeAttr('disabled');
}
}
function doReverseSearch(telValue, pageIdx, methodUrl){
$.ajax({
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
</script>
PS: I'm using this code to modify the display of the web page, depending on the result of a search made by the user.

I've changed the approach I was using. Now, I've changed my model so it contains the data I want to display, like (CountResult, PageCount). And it works fine now.

Related

Fetching Cities dynamically in Asp.net HTML control

I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}

Returning Json Data From Controller to View ASP.NET MVC

I am trying as the title says to return a Json message from the Controller to the View after it validates.
I have made a breakpoint, and I know that the code works from Controller side, and that my JavaScript calls with success the ActionResult now. How do I display that message in the View?
There are two buttons, stamp in and stamp out. If the user stamps in twice, it should get a message, same with stamp out. I have two ActionResults who are indentical except some message and string changes.
Controller:
[HttpPost]
public ActionResult CreateStamp(Stamping stampingmodel)
{
var validateMsg = "";
stampingmodel.Timestamp = DateTime.Now;
stampingmodel.StampingType = "in";
if (stampingmodel.User == null || ModelState.IsValid)
{
var idValidated = db.Users.Find(model.UserId);
if (idValidated != null)
{
var stamp =
db.Stampings.Where(s => s.UserId == stampingmodel.UserId)
.OrderByDescending(s => s.Timestamp)
.FirstOrDefault();
if (stamp.StampingType == stampingmodel.StampingType)
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped Twice In A Row!";
}
}
else
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped In, Welcome.";
}
}
}
db.Stampings.Add(stampingmodel);
db.SaveChanges();
}
return Json(new {Message = validateMsg });
JavaScript:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
}
});
});
View:
<input type="text" id="idUser" class="form-control" />
<br />
<input type="submit" value="IN" id="stampInBtn" />
I have more code inside the View of course; divs, head, body, title and scripts. But it's perhaps a little irrelevant.
What should I do to successfully show those messages?
Regards.
Add a success function to the ajax call
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: { userId: userId },
success: function(data) {
// data contains the value returned by the server
console.log(data);
}
});
So if the controller returns
return Json("This is a message");
the value of data will be "This is a message". Note the return value can be a complex type or a partial view
You are getting the value of $("#userId"), but your input has an id of idUser.
Try making your input:
<input type="text" id="userId" class="form-control" />
Also it would be a good idea to provide your Stamping model structure as it seems that you only pass the user id in your post and nothing else.
Change your javascript code as following:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
},
success: function(data) {
var objData= jQuery.parseJSON(data);
alert(objData.Message );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
});

The resource cannot be found in Ajax function

I'm using C# asp.net mvc.
I wrote a Ajax function in my Home controller - > index.cshtml.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
data: ({}),
success: function (data) {
$('#alertList').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
</script>
this is my function in Home controller
public IList<tblInsurance> getAlertsIns()
{
var query = (from i in db.tblInsurances
where i.status == true && i.EndDate <= DateTime.Today.AddDays(7)
select i).ToList(); ;
return query;
}
public string getAlerts()
{
string htmlval = "";
var InsExpirList = getAlertsIns();
if (InsExpirList != null)
{
foreach (var item in InsExpirList)
{
htmlval += item.tblContractor.Fname + " " + item.EndDate + "<br />";
}
}
return htmlval;
}
But ther is error and it says " The resource cannot be found."
POST http://localhost:49368/Home/getAlerts 404 Not Found
what is wrong with my code?
If you want your controller action to accept POSTs, you must decorate it with an attribute specifying that fact:
[HttpPost]
public string getAlerts()
{
// ...
}
In this case, however, it seems like a GET request would be more appropriate (your action is called getAlerts after all). If that's the case you can omit the accepted verb, or use [HttpGet] instead. You would also have to change your AJAX request:
$.ajax({
type: 'GET',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
/* ... */
});

Ajax call does not work in mvc 4

I am pulling my hair. For the love of my life I cannot make this work. I have a form in my view:
<div id="cancel" class="cancel">
<form method="post" class="cancelForm">
<input type="hidden" class="cancelId" name="cancelId" value="#appliedLvl.LeavesId" />
<input id="cancelMe" class="cancelMe" type="submit" value="Cancel"/>
</form>
</div>
The javascript
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});
And the Controller
[HttpPost]
public ActionResult Cancel(Guid cancelId )
{
//do stuff here
return PartialView();
}
I always get into the error function of the ajax. No matter what I have tried. This same javascript code works perfectly on my php projects. Don't know what is wrong here. Thanks in advace for any help.
Edit
The error here was the fact that I was expecting in the Action a Guid not a string!
You aren't passing in a cancelId parameter, so it isn't seeing your controller method.
$(document).ready(function () {
$(".cancelForm").submit(function () {
var MYcancelId = $('.cancelId').val();
$.ajax({
type: "POST",
url: "/Home/Cancel",
data: { cancelId = MYcancelId },
success: function (result) {
alert("ok");
},
error: function (request, status, error) {
debugger;
confirm(request);
}
});
})
});

Ajax function doesn't seem working

I'm developing an online application of tennis club management... (MVC 3, Entity Framework Code first,...)
I've an Interface that allows the user to consult the available tennis court :
In my "AvailableCourtController", I've a function which return the tennis courts :
[HttpPost]
public JsonResult GetTennisCourt(DateTime date)
{
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);
return Json(courts, JsonRequestBehavior.AllowGet );
}
So, I would like to change the color of my label if the tennis court is busy or free... For that I use "Ajax":
"View" (What I've tried to make)
<input id="datePicker" type= "text" onchange="loadCourts"/>
<script type="text/javascript">
$('#datePicker').datetimepicker();
</script>
<script type="text/javascript">
function loadCourts() {
var myDate = $('#datePicker').value();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
I never get the message "test"... So I have make something wrong with my Ajax function or my controller's method... My goal is to get the tennis court, check if they're free or not and change color in red if busy, and in green if free...
Can you help me to find what I'm doing wrong please? Sorry :( But I'm a beginner with Ajax...
This line is not passing a date in the querystring:
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
should be:
url: ("/AvailableCourt/GetTennisCourt?date=" + myDate),
EDIT: Also you're not getting the value correctly:
var myDate = $('#datePicker').value();
should be:
var myDate = $('#datePicker').val();
Your datetimepicker() call has to occur inside of a document.ready. Here is the corrected code:
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(loadCourts);
});
function loadCourts() {
var myDate = $('#datePicker').val();
$.post({
data: "{ 'date' : " + myDate + " }",
url: (#Url.Action("AvailableCourt", "GetTennisCourt"),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
}
Your url is wrong :-)
Should be:
$.ajax({
url: "/AvailableCourt/GetTennisCourt?date="+myDate, // without ( )
success: function (data) {
alert('test');
//change label's color
}
});
A more verbose AJAX call:
$.ajax({
type: 'POST',
data: "{ 'date' : " + myDate + " }",
url: '/AvailableCourt/GetTennisCourt',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000, // 8 second timeout
success: function (msg) {
},
error: function (x, t, m) {
if (t === "timeout") {
HandleTimeout();
} else {
alert(t);
}
}
});
I agree with #CAbbott that your URL was not created correctly. But with date values (and multiple query string values in general), you may be better off adding your date parameter in a data object literal in your ajax call:
function loadCourts() {
var myDate = $('#datePicker').val();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt"),
data: { date: myDate },
success: function (data) {
alert('test');
//change label's color
}
});
}
jQuery will append your data onto the querystring for you and format it appropriately.
From the jQuery API docs:
The data option can contain either a query string of the form
key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
'value2'}. If the latter form is used, the data is converted into a
query string using jQuery.param() before it is sent.

Categories

Resources