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

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

Related

Model vs List<Model> when sending post request to controller using Ajax

I have been trying to send a list model to controller using ajax but it seems it is not working at all
Model
public string MyModel {
public string myfieldName {get;set;}
}
controller
public JsonResult Create(List<myModel> list)
{
return Json("Success");
}
post request
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so when I send this through, I check the browser and I can see that the request payload is sent with json object list
However when I go to controller the list is not binding it at all, so I check the http.context to check the request payload there and it all empty.
on the other hand when I change the controller like below
sending request with only model
public JsonResult Create(myModel data)
{
return Json("Success");
}
and change the js with below
$("body").on("click", "#btnSave", function () {
var data ={};
data.myfieldName= "test";
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
the only difference here is that I don't send as json, so my question what is the is the difference between sending model vs a list of model using ajax
and what can I change to get the controller to bind the data or accept a list of model data
noting i'm using .Net core 2.0
Thank you
I usually use this method to send my Model as a List to my Controller method. I will try to show you regarding your scenario, how you can do this:
AJAX:
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "#Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
And you can receive your Model like this in your Create method:
Make sure to import the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization
[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}
//Do something with the list here
return Json("Success");
}
Hope this helps you out.
Another method would be to utilize unobtrusive AJAX. All you would need is to install Microsoft jQuery unobtrusive AJAX from your Nuget Package Manager.
Then, in your view, call the following:
#{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
{
HttpMethod = "POST",
// ...
}
}))
{
// Html code goes here
}
And also make sure that you include this at the bottom of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then, you can have a normal ActionResult setup (instead of JsonResult) for your controller and accept an argument of List list.

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.

Transfer resource file data from controller to js file

I need to get the resource data on js file.
so I want to transfer the resource data from controler action to js file by ajax callback.
How to do this?
I'm working in asp.net mvc 5
I'm do it's so:
controller Action:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult GetCultureResource()
{
ResourceSet resourceSet =
Resources.Resources.ResourceManager.GetResourceSet(new System.Globalization.CultureInfo(cultureName), true, true);
var dicResource= resourceSet.Cast<DictionaryEntry>()
.ToDictionary(x => x.Key.ToString(),
x => x.Value.ToString());
var jsonString = JsonConvert.SerializeObject(dicResource);
return Json(new { resource = jsonString});
}
javascript fanction:
function SetCultureResource() {
$.ajax({
type: "POST",
url: "/ControllerName/GetCultureResource",
dataType: "json",
success: function (data) {
var obj = jQuery.parseJSON(data.resource);
//do somthing as this with Resource
//alert(Resource.BeforLogOut);
},
error: function (data) {
}
});
}

MVC How to pass data from view to model using Ajax

Hello I'm posted a question asking what to use to send information from a view to a model. I realize that the info needs to be send to the controller and then to my model. I got some code that send info from my view to my controller:
Here is the Ajax:
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content fom the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
alert(data);
},
error: function (e) { alert(e); }
})
});
});
An this is the code in my controller:
[HttpPost]
public ActionResult processCommand(string cmd)
{
return Json(cmd);
}
I've tested it and send my input in json. However my problem is, I don't know how to take the string out of that and send it to my model. Please any help would be appreciated.
As stated in the comments to your question, the terminology you use is a little confusing, but if understood your question correctly, you want an action on your controller on the server to accept a 'command' and work with it.
The following post can be made, in order for the ajax post to successfully hit the action :
$('#cmdSend').click(function () {
var cmdInput = document.getElementById('cmdInput').value;
$.ajax({
url: 'terminal/sendInfo',
type: 'POST',
data: {cmd : cmdInput},
dataType: 'json',
success: function (data) {
//What you want to do with the returned string with data.cmd
}
});
});
The controller action would be like the following :
public class TerminalController : Controller
{
[HttpPost]
public JsonResult sendInfo(string cmd)
{
//Do what you want to do with 'cmd' here.
return Json(new { cmd = "Whatever you want to send" }, JsonRequestBehavior.AllowGet);
}
}
Hope this helps!

ASP.NET MVC Partial view ajax post?

Index.html (View)
<div class="categories_content_container">
#Html.Action("_AddCategory", "Categories")
</div>
_AddCategory.cshtml (PartialView)
<script>
$(document).ready(function () {
$('input[type=submit]').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
dataType: "json",
data: $('form').serialize(),
success: function (result) {
$(".categories_content_container").html(result);
},
error: function () {
}
});
});
});
</script>
#using (Html.BeginForm())
{
// form elements
}
Controller
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return RedirectToAction("Categories");
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
Question: If operation is success I expect that redirect to another page (Categories). But no action, no error message. If operation is not success, it is working like my expected.
How can I do this? How can I route another page with using AJAX post?
Don't redirect from controller actions that are invoked with AJAX. It's useless. You could return the url you want to redirect to as a JsonResult:
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return Json(new { redirectTo = Url.Action("Categories") });
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
and then on the client test for the presence of this url and act accordingly:
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
// The operation was a success on the server as it returned
// a JSON objet with an url property pointing to the location
// you would like to redirect to => now use the window.location.href
// property to redirect the client to this location
window.location.href = result.redirectTo;
} else {
// The server returned a partial view => let's refresh
// the corresponding section of our DOM with it
$(".categories_content_container").html(result);
}
},
error: function () {
}
});
Also notice that I have gotten rid of the dataType: 'json' parameter from your $.ajax() call. That's extremely important as we are not always returning JSON (in your case you were never returning JSON so this parameter was absolutely wrong). In my example we return JSON only in the case of a success and text/html (PartialView) in the case of failure. So you should leave jQuery simply use the Content-Type HTTP response header returned by the server to automatically deduce the type and parse the result parameter passed to your success callback accordingly.
The ajax call you made should not be able to redirect the whole page. It returns data to your asynchronous call only. If you want to perform a redirect, i
the javascript way to redirect is with window.location
So your ajax call should look like this:
<script>
$(document).ready(function () {
$('input[type=submit]').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
dataType: "json",
data: $('form').serialize(),
success: function (result) {
window.location='#Url.Action("Categories")';
},
error: function () {
}
});
});
});
</script>
In you action method, instead of returning a partial or redirect, return Json(true);
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
return Json(true);
}
else
{
return Json(false);
}
}

Categories