AJAX call not acting as expected - javascript

I am attempting to use an AJAX call to render a partial view when a radio button is selected. I have searched and have tried what appears to be the best approach via comments on Stack. When I click the radio button, I have no result, in debug, I get a Status Code: 500 Internal Server Error? Any assistance would be great.
Partial View Names:
_BOA.cshtml
_TA.cshtml
_MNB.cshtml
View:
<td class="radio-inline">
#Html.RadioButton("bankSelect", "MNBConvert", false, new { #class = "radioMNB" }) MNB Conversion
#Html.RadioButton("bankSelect", "BOAConvert", false, new { #class = "radioBOA" }) BOA Conversion
#Html.RadioButton("bankSelect", "TAConvert", false, new { #class = "radioTA" }) TA Conversion
</td>
Javascript:
<script src="~/Scripts/jquery-1.9.0.js"></script>
<script type="text/javascript">
$(function () {
$("[name=bankSelect]").on('change', function () {
// var $radio = $(this);
var checked = $("input[name='bankSelect']:checked").val();
$.ajax({
url: '#Url.Action("GetBankToConvert", "Home")',
data: checked,
type: 'GET',
success: function (data) {
$("#renderPartialView").html(data);
}
});
});
});
</script>
Controller:
[HttpGet]
public ActionResult GetBankToConvert(string bankSelect)
{
if (bankSelect == "MNBConvert")
{
return PartialView("_MNB");
}
else if (bankSelect == "BOAConvert")
{
return PartialView("_BOA");
}
else
{
return PartialView("_TA");
}
}

You aren't sending a key/value pair as data, only a value.
Try
$.ajax({
url: '#Url.Action("GetBankToConvert", "Home")',
data: {bankSelect: checked },
type: 'GET',
success: function (data) {
$("#renderPartialView").html(data);
}
});
WHen in doubt, inspect the actual request in network tab of browser dev tools to see exactly what is sent and received among all the other components of a request

Related

Table not refreshing after post function in JQuery and ASP.NET CORE

I have made a filtering method. This method is working like a charm and when I type something the table updates to the search string. This is my method for the search:
loadList() {
var searchString = $(".search-input").val();
$.post('/Translation/List?searchString=' + searchString, function (data) {
$(".table-content-view").html(data);
});
}
And when I wanna insert a new record I call this method:
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
if (response.success === true) {
loadList();
}
}
});
}
This method works fine (confirmed with postman and chrome dev tools). The problem is I need to press F5 to see the new record instead that it refresh instantly. As you can see I call the method LoadList() to refresh the table but this doesn't work.
NOTE:
I use a partial view for the table.
This is my C# method for the list:
[HttpPost]
public async Task<IActionResult> List(string searchString)
{
var translations = _context.translation.AsQueryable();
translations = translations.OrderBy(x => x.CORETRANSLATIONID);
if (!String.IsNullOrEmpty(searchString))
{
translations = translations.Where(x => x.ORIGINAL.Contains(searchString));
}
return PartialView(await translations.ToListAsync());
}
Can someone point me in the right direction?
In my post method in JQuery I changed it too
saveTranslation() {
$.ajax({
url: '/Translation/Edit',
data: new FormData($(`${tr.selectedclass} #translation-form`)[0]),
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
loadList();
}
});
}
The if statement was not necessary.

Passing data from javascript to action method in asp.net MVC

I have placed a bootstrap toggle switch in my application
Now i want is to send the On and Off values to my action method
Bellow is my razor syntax
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>}
For passing data to controller from JS i have searched many articles and found that ajax is the way to do it
Bellow is my script for ajax inside JS
<script>
var cmdName = '#Session["cmdName"]';
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'On',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'Off',
success: function () {
alert(data)
}
});
}
}); </script>
I have also used session variable but getting null value in it
Bellow is my controller code
public ActionResult MultiGraph(string search, string start_date, string End_date, string cmdName, int? page)
{
//search contain serial number(s)
//cmdName is for input checkbox
}
Bellow is the image for my switch button
When i switch it to Off then this Off string should be sent to my action method and vise versa
Updated Code
After reading comments i have done the following changes to my code
I have added a new action method of type Post
[HttpPost]
public ActionResult ToggleSwitch (string search, string cmdName)
{
List<SelectListItem> items = new List<SelectListItem>();
var dtt = db.ADS_Device_Data.Select(a => a.Device_Serial_Number).Distinct().ToList();
foreach (var item in dtt)
{
if (!string.IsNullOrEmpty(item))
{
items.Add(new SelectListItem { Text = item, Value = item });
}
}
ViewBag.search = items;
return View();
}
Bellow are changes in my razor
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "Off"}',
success: function () {
alert(data)
}
});
}
});
But still i get no alert message, when i inspect element i found this error
I am stuck to this problem from almost 2 days
Any help would be appreciated
You need to use the $ character to invoque jQuery functions and pass your data from page to controller with the same name you defined in the action method using Json notation:
'{"cmdName": "On"}',
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
Furthermore, you might need to decorate your mvc action whith the [HttpPost] attribute.

Unable to render partial view in view when using $.ajax

Not sure what I'm missing in my code. I have a view with a few radio buttons and want to render a different partial view when a radio button is selected. Here is my code:
Controller
public ActionResult Method(string value)
{
var pv = "";
switch (value)
{
case "radio1":
pv = "_XPartial";
break;
case "radio2":
pv = "_YPartial";
break;
case "radio3":
pv = "_ZPartial";
break;
}
return PartialView(pv);
}
View div to render partialview
<div id"="renderarea">
#*Render partialview here.*#
</div>
JavaScript
$(document).ready(function () { GetPartial(); });
$("input[name='RadioOptions']").on('change', function () { GetPartial(); })
function GetPartial() {
var selection = $("input[name='RadioOptions']:checked").val();
//alert(selection) -- THIS ALERT SHOWS THE CORRECT VALUE
$.ajax({
url: '#Url.Action("Method", "Home")',
data: {'value' : selection},
contentType: 'application/html',
type: 'GET',
dataType: 'html',
success: function (pv) {
//alert(pv) -- THIS ALERT SHOWS THE HOLE PARTIAL VIEW HTML CODE
$("#renderarea").html(pv); -- THIS HERE ISN'T WORKING
}
});
}
The part that seems to not be working is $("#renderarea").html(pv); and I really don't know why. Have someone had this issue before?
Try this, it should be work:
$.ajax({
url: "/Home/Method",
data: selection,
type: 'GET',
dataType: 'html',
success: function (pv) {
$("#renderarea").html(pv);
}
});

Mvc 5 ajax display collection doesn't work

I have class :
public JsonResult refreshMap(int time)
{
// Some code before
List<User> lista = new List<User>();
lista.Add(usr11);
lista.Add(usr22);
return Json(lista, JsonRequestBehavior.AllowGet);
}
And view :
<div id="PersonList"></div>
<input type="radio" name="time" value="5">Last 5min
<input type="radio" name="time" value="15">Last 15min
And the attached JS :
$(document).ready(function () {
$(':radio[name="time"]').change(function () {
$.ajax({
url: '/Connection/refreshMap',
cache: false,
dataType: "JSON",
data: {
time: $(':radio[name="time"]:checked').val()
},
success: function (data) {
$.each(data, function (index, value) {
$("#PersonList").append(value.Email);
});
}
});
return false;
});
});
And I want do this : when i checked radio I use method and I get data from controller and I want display this collection. But my function in ajax doesn't work. But when I return in method refreshMap only one object: [...] return Json(usr11, JsonRequestBehavior.AllowGet);
And if I change my ajax function like below, this work !
$(document).ready(function () {
$(':radio[name="time"]').change(function () {
$.ajax({
url: '/Connection/refreshMap',
cache: false,
dataType: "JSON",
data: { time: $(':radio[name="time"]:checked').val() },
success: function (data) {
$("#PersonList").append(data.Email +"</br>");
}
});
return false;
});
});
Have you idea what I can repair it?
data comes wrapped in 'd', by using $each you seem to enter the data object but in the second one it does not 'project' the values.
i usually do if(data.d){...} just to make sure the data will not shortcircuit my code, or the absence of it to be concrete.
Will also look at what type is 'Email' and how it serialised.

Javascript firing, without me asking it to

I have an MVC4 application, and on the layout (master page for the oldies), I have some javascript:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
This simply logs in a user.
This is working fine.
However, on another screen I now have some new javascript, which does similar function, by taking data from a form, and passing it to a controller to handle.
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmitNewCard').on('click', function () {
var data = { cardNumber: $('.txtNewCardNumber').val(), cardHolder: $('.txtNewCardHolder').val(), expiryMonth: $('.txtNewExpiryMonth').val(), expiryYear: $('.txtNewExpiryYear').val(), active: $('.txtNewActive').val(), accountId: $('.Id').val() };
$.ajax({
url: '#Url.Action("SaveBankCard", "BankAccount")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
console.log(result.toString());
if (result.Success == 'true') {
// window.location = '#Url.Action("Index", "Home")';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no");
}
});
});
});
</script>
When I click the save button that this code is linked to, the code fires, the controller method goes well, the data is stored, but then, when I refresh the screen, I get an 'Undefinied' error coming from the LOGIN script above. It seems to fire when the page is reloaded. I am unsure why it's firing. It should just load, ready to fire, but it seems to be called, and fails.
The controller that it calls is this:
public ActionResult SaveBankCard(string cardNumber, string cardHolder, int expiryMonth, int expiryYear, string active, int accountId)
{
var card = new AccountCardDto
{
Id = 0,
AccountId = accountId,
Active = active == "on",
CardHolderName = cardHolder,
CardNumber = cardNumber,
ExpiryDate = new DateTime(expiryYear, expiryMonth, 1)
};
int id = new BankAccountService().SaveCard(card);
return RedirectToAction("EditBankAccount", new { bankAccountId = accountId });
}
The problem happens on the RedirectToAction... when that view reloads, which includes the Layout, the Layout javascript fires.
EDIT: I now see that it's the btnSubmitNewCard javascript that is fired twice. Once when the click event happens (expected), and then again when the postback happens. Why is the second event happening?
Check with this: -
$('.btnSubmitNewCard').click(function () {...});
You are getting Undefined in the line that checks status:
if (result.Success == 'true') {
Because result contains string with html response of the view for the EditBankAccount action and does not have "Success" property.
You can put breakepoint in debugger and see. You can use debugger; statement as breakpoint

Categories