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

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.

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.

ASP.NET Ajax Serialize Form and pass other parameters to Controller

I would like to send more than just the serialized form data to the controller. for example I'd like to include other parameters. Something like:
data: {record:formData, searchLetter:letter, page:pageNum}
However, whenever I try this, the model does not properly bind, it ends up being null.
Javascript:
$(document).ready(function () {
$('.save-attendance-record-button').click(function() {
$('#form-edit-attendance-record').on('submit', function(e) {
e.preventDefault();
return false;
var formData = $(this).serialize();
$.ajax({
dataType: 'html',
method: 'post',
url: resolveUrl('~/Home/EditAttendanceRecord'),
data: { record:formData, searchLetter:"a", searchTerm:"", page:1 }
})
.done(function (data) {
e.preventDefault();
$('#attendance-records-partial').html(data);
});
e.preventDefault();
});
$('#form-edit-attendance-record').submit();
});
});
Controller:
[HttpPost]
public ActionResult EditAttendanceRecord(AttendanceRecord record, string searchLetter, int? page)
{
//...
}
Edit 1
Here is what formData looks like when it is the only argument:
ID=2&InviteeFirstName=Test%20K.&InviteeLastName=Test&InviteeCheckedIn=true&InviteeCheckedIn=false&GuestName=test&GuestCheckedIn=true&GuestCheckedIn=false&RSVP=
If I have multiple parameters (which is what i want) the request header looks like this:
record=ID%3D2%26InviteeFirstName%3DTest%2520K.%26InviteeLastName%3DTest%26InviteeCheckedIn%3Dfalse%26GuestName%3DWOW%26GuestCheckedIn%3Dtrue%26GuestCheckedIn%3Dfalse%26RSVP%3D&searchLetter=a&searchTerm=&page=1
or parsed:
record:ID%3D2%26InviteeFirstName%3DTest%2520K.%26InviteeLastName%3DTest%26InviteeCheckedIn%3Dfalse%26GuestName%3DWOW%26GuestCheckedIn%3Dtrue%26GuestCheckedIn%3Dfalse%26RSVP%3D
searchLetter:a
searchTerm:
page:1

AJAX call not acting as expected

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

Convert JQuery ajax GET to POST

I have this jquery ajax get method on an Index razor in my application:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "GET",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
var count = 0;
$.each(data, function (index, value) {
$("#ulMessages").append("<li>" + value + "</li>");
count++;
});
// Assume validation errors if more than 1 message
if (count > 1) {
$("#btnSubmit").removeAttr("disabled");
}
}).fail(function () {
$("#ulMessages").append("<li>An error occurred. Please try again later</li>");
$("#btnSubmit").removeAttr("disabled");
}).always(function () {
$("#imgAjaxLoader").hide();
});
This calls a method within the api/project controller that returns a list of strings:
[HttpGet]
public List<string> SubmitProjectForPreapproval(int projectId)
{ ... }
What I want to do is convert this to an ajax post method. I've been struggling to do just that for the better part of the day. My question is, what is everything that needs to change in order for this to happen? e.g. - change attribute of the method to [HttpPost], and how do I send it the route value? (int pojectId)
Edit: If I do this it works for some reason:
public List<string> SubmitProjectForPreapproval(/*int projectId*/)
{
int projectId = 3308;
...
}
Not sure why it doesn't find my method if I have the parameter there.
I'm not sure how the #Url stuff formats with your system - but just changing it to something like:
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: { projectId: "#ViewContext.RouteData.Values["ProjectId"]" }
}).done(function (data) {
If you're bit:
#Url.Action("SubmitProjectForPreapproval
..actually has any ?xxx values in it, you also need to add them into the data: { ... }
The problem was indeed the way I was sending the data to the controller action. I fixed it by doing the following:
Alter the ajax method (make use of JSON.stringify):
var projectIdObject = {
ProjectId: "#ViewContext.RouteData.Values["ProjectId"]",
}
$.ajax({
url: "#Url.Action("SubmitProjectForPreapproval", "api/Project")",
type: "POST",
cache: false,
data: JSON.stringify(projectIdObject),
contentType: 'application/json',
}).done(function (data) { ... }
Add a class to take this stringified value:
public class ProjectIdObject
{
public string ProjectId { get; set; }
}
Alter the controller action method to receive this new object and extract the value I want:
[HttpPost]
public List<string> SubmitProjectForPreapproval(ProjectIdObject projectIdObject)
{
int projectId = int.Parse(projectIdObject.ProjectId);
...
}

How to properly render the return of AJAX POST MVC 4

I'm using MVC 4 and I am trying to send a post request and I am getting a successful return from my controller with the resulting view in HTML form, but I'm not sure what to do with it at that point.
JS
$("form").submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
}
});
my controller
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
So you can see that my controller either returns a View or a RedirectToAction. In the success callback of my ajax call I am doing the following: $("#content").html(data);
But nothing seems to happen. Can someone help push me in the right direction of properly handling the return of the controller action.
Thank you so much!
If I understand correctly, you have a Create Event form on your page and you want to send an AJAX request to create a new event. Then you want to replace a section in your page #content with the results of the CreateEvent action.
It looks like your AJAX is set up correctly so that CreateEvent returns a successful response. I think you're now confused about the response. You have several options but let's choose two.
JSON response
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return Json(event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
...
Now you need to generate html markup from the JSON and insert it into #content.
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
var obj = JSON.Parse(data);
var html; // build html with the obj containing server result
$("#content").html(html);
}
})
or HTML fragment
Instead of returning a full page with a Layout defined we'll return just a PartialView without Layout and all the head and script tags.
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return PartialView("CreateEventResult", event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
}
Now make a new partial view CreateEventResult.cshtml (Razor)
#model Namespace.EventModelResult
# {
Layout = null;
}
<div>
<!-- this stuff inserted into #content -->
#Model.Date
...
</div>
and the javascript is unchanged
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
Edit:
If your Event creation fails for any reason after you have validated the input, you'll have to decide how you want to respond. One option is to add a response status to the object you return and just display that instead of the newly created Event.

Categories