Send data from layout to controller Asp.Net MVC - c#

I have a switch button on my navbar on my layout view, when I click the button It changes the value and send it to the controller:
<input type="button" id="switchbutton" value="Weekend" style="color:blue" onclick="toggle(this)" >
<script type="text/javascript">
function toggle(button) {
switch (button.value) {
case "Weekend":
button.value = "Week";
break;
case "Week":
button.value = "Weekend";
break;
}
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{param: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
}
</script>
On the controller I receive the value and send it to an If statement that executes a function depending on the value received.
private string SwitchVal;
[HttpPost]
public string AjaxMethod(string param)
{
var d = string.Empty;
switch (param)
{
case "Weekend":
d = "Week";
break;
case "Week":
d = "Weekend";
break;
}
SwitchVal = d;
return d;
}
public JsonResult ModelsUpdate(string SwitchVal)
{
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
The problem is that I do click on the button and I don't see any change, It seems that the value only arrives to the controller the first time. Can anybody help me on this?

It doesn't work like that. You can't hold the values in server side for multiple different requests. Maybe you can use Session to perform it but why don't you post the data ModelsUpdate action instead of AjaxMethod. In your case, I couldn't understand the purpose of AjaxMethod.
public JsonResult ModelsUpdate(string SwitchVal)
{
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
return Json(resultminDate);
}
Ajax call looks like
$.ajax({
type: "POST",
url: "/Home/ModelsUpdate",
data: '{SwitchVal: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});

Related

Jquery UI Modal Dialog Not Working Properly

I created a jQuery modal password dialog box to redirect to a page for password validation.
The modal dialog appears alright, but instead of executing the method that handles the password validation it instead shows the error [object Object] on a the browsers alert dialog. I'm trying to figure out what I'm doing wrong here.
Below is my code:
JavaScript/jQuery
$(document).on("click", "[id*=lnkView1]", function() {
$("#dlgPassword").dialog({
title: "View Details",
buttons: {
Go: function() {
var valPassword = $("[id*=cpgnPassword]").val();
var hdfCamId = $('#<%=rptCampaigns.ClientID %>').find('input:hidden[id$="hdfCampaignID"]').val();
$("[id*=hdfCampaignID2]").val(hdfCamId);
//var jsonObj = '{password: "' + valPassword + '"}';
var res;
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{password: "' + valPassword + '"}',
dataType: 'json',
url: 'CampaignsList.aspx/ValidatePasswordWM',
success: function(data) {
alert('successful')
},
error: function(err) {
alert(err.toString());
}
});
$(this).dialog('close');
}
},
modal: true
});
return false;
});
Code-Behind
protected void ValidatePassword(object password)
{
var campaign = new CampaignsService().GetByCampaignId(hdfCampaignID2.Value);
if (campaign != null)
{
if (campaign.Password.Equals(password))
Response.Redirect("CampaignDetails.aspx?CampaignID=" + hdfCampaignID2.Value);
}
}
[WebMethod]
public static void ValidatePasswordWM(object password)
{
CampaignsList page = new CampaignsList();
page.ValidatePassword(password);
}
Can someone help me figure out what's wrong?
You need the appendTo property on your dialog so it gets added to the form properly.
$("#dlgPassword").dialog({
title: "View Details",
appendTo: "form",
buttons: {
...
Instead of err.toString(), try err.message
This code shows a products cadastre at jQuery UI. When OK button pressed, re-populate dropdownlist.
Javascript:
$dialog = $("#dlgCadastroProduto").dialog({
modal: true,
autoOpen: false,
height: 500,
width: 700,
buttons: {
Ok: function () {
$(this).dialog("close");
$("#lstProducts").empty();
$("#lstSelectedProducts").empty();
$.ajax({
type: "GET",
url: '/Produto/jsonLoad',
async: true,
dataType: 'json',
success:
function (data) {
//alert('sucesso');
$.each(data, function (index, value) {
//insere elemento na droplist
$("#lstProducts").append('<option value='+value.ID+'>'+value.Descricao+'</option>')
});
},
error: function (data) {
//alert(data);
}
});
}
}
});
$("#btnCadastroProduto").button().on("click", function () {
$dialog.dialog("open");
});
Code-Behind at Controller:
public JsonResult jsonLoad()
{
var lista = _produtoBLL.FindAll();
var xpto = lista.Select(x => new { Id = x.ID, Descricao = x.Descricao });
return Json(xpto, JsonRequestBehavior.AllowGet);
}
I hope i have helped
This is just sample code you can you with yours
Client Side
var mparam = "{param1:'" + mvar1 + "',param_n:'" + mvar_n + "'}";
$.ajax({
type: "POST",
url: "file_name.aspx/web_method",
data: mparam,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Response) {
try {
var msdata = JSON.parse(Response.d);
if (msdata.err == "0") {
location.replace("newlocation");
}else{
alert("Error:" + msdata.msg);
}
} catch (e) {
alert("Error in JSON parser error:" + e.description);
}
},
error: function (medata) {
alert("Internal Server Error:" + medata);
}
});
Server Side
[System.Web.Services.WebMethod]
public static string web_method(string param1, string param_n)
{
string strerror = "0", strmessage = "";
try
{
strerror = "0";
}
catch (Exception ex)
{
strerror = "2";
strmessage = ex.Message;
}
return "{\"err\":\"" + strerror + "\",\"msg\":\"" + strmessage + "\"}";
}

getting error on passing string as json object in ajax jquery

I'm trying to pass a string in code behind method using ajax jquery but getting a stupid error. If I pass integer only then it works fine but in case of string it's not working
this is what i've tried
csharp code
public static string GetQuickVD(string key)
{
return key.ToString();
}
jquery
$(document).ready(function () {
GetQuickVL();
});
function GetQuickVL() {
var Nid = new Array();
for (var key in localStorage) {
if (key.substring(0, 4) == "vhs-") {
Nid += key.replace('vhs-', '') + ",";
}
}
$.ajax({
type: "POST",
url: "QuickViewList.aspx/GetQuickVD",
data: '{key: ' +'345,' + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.response);
},
error: function (response) {
alert(response.error);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
use like this
data: {key: "345" }
You can also use like,
type: "GET",
url: "QuickViewList.aspx/GetQuickVD?key=355",
Edit
data: JSON.stringify({"key": "345"}),

MVC post with data and return json data

I have a controle like this
public JsonResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
I need to get that by following json by ajax request
var sizes = [];
$.ajax({
type: 'POST',
async: false,
data: { 'Id': selectedId },
url: "/<Controler name>/GetSizes",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
return false;
},
success: function (result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}
});
But this give me an Server error. How can i fix this.
replace your
url: "/<Controler name>/GetSizes",
by
url: "#Url.Action("GetSizes", "Controller_Name"),
and is you Ajax will have to be
async: false?
then try to use this as your Action
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
Also, try to put a break point on your action and see in debug mode if your Ajax reaches your Action.
this my demo, you can do the same:
$.ajax({
url: '#Url.Action("CheckCity", "BookingStarts")',
data: { packageId: packageid, cityId: valuecities[valuecities.length - 1] },
type: 'POST',
dataType: 'json',
success:
function(result) {
if (result.Status == true) {
$('#CheckoutDateHotel_#item.CityId').val(result.Date);
}
}
});
in controller :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CheckCity(int packageId, int cityId)
{
var packageCityModel = PackageDetails.GetPackageCitiesByPackageId(packageId).OfType<HMSService.PackageCity>();
var package = new PackageReservationMasterDal();
var itemPackage = package.GetPackageDetailByPackageId(packageId);
var result = "";
var city = packageCityModel.FirstOrDefault(x => x.CityId == cityId);
if (city != null)
{
result = itemPackage.TravelDateFrom.AddDays(city.NoOfNights).ToShortDateString();
}
return Json(new { Status = true, Date = result });
}
See the problem here is that you have not stringified your Data Transfer Object(DTO).
A cleaner approach will be this.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.0/json3.js"></script>
<script type="text/javascript">
var sizes = [];
var DTO = { 'Id': selectedId };
$.ajax({
type: 'POST',
async: false,
data: JSON.stringify(DTO),
url: "#Url.Action("GetSizes", "Home")",
dataType: 'json',
contentType: 'application/json'
}).done(function(result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}).fail(function(xhr) {
alert('Error: ' + xhr.statusText);
return false;
});
</script>
Please note the use of
JSON.stringify
#Url.Action helper
jqXHR.done(function( data, textStatus, jqXHR ) {});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
Also you are using async=false which I guess is to grab all the sizes before exiting from the function. jQuery.deferred will be an interesting read.

returning complete page HTML instead of string output in JSON response

I am trying to achieve a simplest task through ajax using web method . My web method as follow
[WebMethod]
public static string GetDate()
{
return string.Format("says {0}", DateTime.Now.ToString("r"));
}
and ajax code as follow
$(document).ready(function() {
$("#Result").click(function() {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "test1.aspx/GetDate",
data : "{}",
contentType: "application/json",
dataType: "json text",
success: function(rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function(rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
console.log(rsp);
console.log(rsp.responseText);
}
});
});
});
but status says OK and 200 status code, but instead of simple string in rsp.d its shows complete HTML of that page self.
You Can Try this Code May be it is Help Full.
$("#Result").click(function () {
alert('Result Clicked');
$.ajax(
{
type: "POST",
url: "Default.aspx/GetDate",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (rsp) {
alert('success');
alert(rsp);
alert(rsp.d);
$('#Result').append(rsp.d);
},
error: function (rsp) {
alert(rsp.status + " " + rsp.statusText + "</br>" + rsp.responseText);
}
});
});

jQuery autocomplete shows undefined values while WebService is returning correct data

$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "MyService.asmx/GetCompletionList",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
This is my jQuery code and WebService method. Can any one help me?. GetCompletionList WebService method returns list of string but autocomplete on TextBox shows undefined for all values
public List<string> GetCompletionList(string prefixText)
{
RegistrationBAL _rbal = new RegistrationBAL(SessionContext.SystemUser);
DataSet ds = new DataSet();
_rbal.LoadByContextSearch(ds, prefixText);
List<string> myList = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
myList.Add((string)row[0]);
}
return myList.ToList();
}
Try to change the data in the ajax call as follows
if the auto complete is done for an asp control
data: "{'prefixText':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
or else give as follows
data: "{'prefixText':'" + document.getElementById("requiredID").value + "'}",
edited answer where the auto complete works
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
}
which resembles your ajax function but in server side I used the web service as below which the get values from the database
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetAutoCompleteData(string PhoneContactName)
{
List<string> result = new List<string>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("select DISTINCT PhoneContactName from PhoneContacts where PhoneContactName LIKE +#SearchText+'%'", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", PhoneContactName);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["PhoneContactName"].ToString().TrimEnd());
}
return result;
}
}
}
}
.. Hope this helps :D

Categories