Where is my "data" Ajax option in Razor syntax? - javascript

In the documentation https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions%28v=vs.118%29.aspx I can't find anything that is the equivalent of the data parameter in something like
$.ajax({
url: '#Url.Action("AutoLocate")',
type: 'GET',
data: postData,
success: function(result) {
// process the results from the controller
}
});
Using Razor syntax for a form, e.g.
#using (Ajax.BeginForm("GenerateMasterLink", "SurfaceAssets", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "masterLinkHolder" })) { ... }
how do I tell it that I want a JavaScript variable, say,
var str = "here's a string, bro!";
to be passed in to the corresponding controller
public ActionResult GenerateMasterLink (string str)
{
...
}
??????

Try like this.
$.ajax({
url: '#Url.Action("AutoLocate")',
type: 'GET',
data: str,
success: function(result) {
// process the results from the controller
}
});
and in controller
public ActionResult GenerateMasterLink (string str)
{
...
}
If you have more than one parameter then
$.ajax({
url: '#Url.Action("AutoLocate")',
type: 'GET',
data: {id: 12,name:'Name'},
success: function(result) {
// process the results from the controller
}
});
public ActionResult GenerateMasterLink (int id,string name)
{
...
}

You can pass form data into the action GenerateMasterLink using a C# type you create in your server code with one property for each of the properties in your javascript object. It might looks something like this:
public class FormData
{
public int PropertyName1 { get; set; }
public string PropertyName2 { get; set; }
}
public ActionResult GenerateMasterLink (FormData form)
{
...
}
Make sure the data being sent is valid JSON (use JSON.stringify() in JavaScript to convert a JavaScript object to JSON). Also, you can get the value into your view using the ViewBag (or model). Here's how you'd set it in the ViewBag:
public ActionResult GenerateMasterLink (FormData form)
{
ViewBag.SomeNameOfYourChoosing = form.PropertyName1;
return View();
}
Then in the Razor:
#ViewBag.SomeNameOfYourChoosing

Related

json string on POST to MVC action method using AJAX is null

I am getting a hard time to find out why the string sent via AJAX request is null. Console.WriteLine(data) shows empty. Status is 200 OK. If I add some code to parse the string received, I get an error stating that JObject.Parse cannot be null. I don't know what am I missing. The javascript code is ok. The action method also seems ok, but my knowledge on Asp.Net Core and MVC is very scarce, so I am not sure. Can someone please point out what am I missing?
The javascript code:
let obj = {email: email_address.value};
let objStringified = JSON.stringify(obj);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: objStringified,
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'text',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
C# code:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] string data)
{
Console.WriteLine(data);
JObject jObject = JObject.Parse(data);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}
The solution on the controller side is
public class AccountCheckModel
{
public string Email { get; set; }
}
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
{
string result = CheckAccountDuplication.Get(data.Email).ToString();
return Content(result);
}
Thanks to all the members who commented on my problem, especially John Glenn who provided a solution. I had been trying for several days but without success. My knowledge of Asp.Net Core is very poor indeed. Thank you very much.
The easiest solution is to create a model representing the JSON data that your controller will receive. For example, create a class like so:
public class AccountCheckModel
{
public string email { get; set }
}
Then, use it as the parameter for your controller method:
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
This is the preferred way to access the request body. To get the request body as a string, you have to jump through some serious hoops.
An alternative way to send your data via AJAX to your Controller:
var json = {
email: email_address.value
};
$.ajax({
type: 'POST',
data: {'json': JSON.stringify(json)},
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
And your Controller:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication(string json)
{
Console.WriteLine(json);
JObject jObject = JObject.Parse(json);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}

Access form data in C# controller from AJAX post

I am sending form data to a c# controller using AJAX, however I don't know how to access the data inside the controller. I am trying to pass the form data into the controller as a Person object but I am just returning system.Models.Person. I am new to C# so any help would be greatly appreciated, thanks a lot.
Javascript
$('#myForm').submit(function(e){
e.preventDefault();
const formData = new FormData(e.target);
$.ajax({
url: '/Home/GetFormData',
type: 'POST',
data: {formData: formData},
success: function(resultData){
console.log(resultData)
},
error: function(){
//do something else
}
})
}
Model
public class Person
{
public string name { get; set; }
public string age { get; set; }
}
Controller
public string GetFormData(Person formData)
{
string name = formData.name.ToString();
return name;
}
The following post will help you
Post Data Using jQuery in ASP.NET MVC
Your code should be
Model class Person.cs
public class Person
{
public string name { get; set; }
public string age { get; set; }
}
jQuery function to get the form data, I am assuming here you have submit button on your form
$(document).ready(function () {
$("#btnSave").click(function () { //Your Submit button
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Home/GetFormData", // Controller/View
data: { //Passing data
name: $("#txtname").val(), //Reading text box values using Jquery
age: $("#txtage").val(),
}
});
});
});
Your HomeController method
[HttpPost]
public ActionResult GetFormData(Person obj)
{
string name = obj.name;
string age = obj.age;
//Once you have data here then you can pass anywhere i.e. database or some other method
return View();
}
Form values in the controller
Let me know, if any clarification required.
Use serialize if you will send form values:
$form = $(this).serialize();
Use FormData if you be sending a file for upload and alike.
And on your data declaration, set it as is (without declaring it as a literal JS object)
data: $form
The final code would look like this:
$('#myForm').submit(function(e){
e.preventDefault();
$form = $(this).serialize();
$.ajax({
url: '/Home/GetFormData',
type: 'POST',
data: $form,
success: function(resultData){
console.log(resultData)
},
error: function(){
//do something else
}
})

.Net core - Ajax post does not pass variables to controller method

When I set a breakpoint on LoadReport, every parameter is null. For some reason the values are not binding to the parameters with the same name.
Javascript/AJAX
$('#savedCriteria').on('change', function () {
var criteriaSelected = $('#savedCriteria option:selected').text();
var data = { actionName: "Daily", reportInput: "ReportDaily", reportCriteria: criteriaSelected };
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: "application/json; charset=utf-8",
url: '#Url.Action("LoadReport", ViewContext.RouteData.Values["Controller"].ToString())',
success: function (data) {
if (data.success) {
alert("Test");
} else {
alert("Test Not Successful");
}
}
});
});
Controller
public void LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
RedirectToAction(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
Default method type is HttpGet, you need to set it to HttpPost.
[HttpPost]
public void LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
RedirectToAction(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
Also keep in mind that with your ajax call you can not use RedirectToAction. You need something like this:
[HttpPost]
public ActionResult LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
Return Json(Url.Action(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
And in your ajax call:
success: function (data) {
window.location.href = data;
}
UPDATE: you also need to create a POCO object and add that to the HttpPost method as parameter instead of separate parameters. Also [FromBody] attribute is needed.
POCO:
public class Data
{
public string actionName { get; set; }
public string reportInput { get; set; }
public string reportCriteria { get; set; }
}
Controller:
[HttpPost]
public JsonResult LoadReport([FromBody]Data data)
{
var reportObject = Activator.CreateInstance(Type.GetType(data.reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(data.reportInput);
return Json(Url.Action(data.actionName, "Reports"));
}

Why does my controller action add 2 new records instead of one

I have a simple razor view with a button that is supposed to add a new record to a table in my SQL DB.
The button has attached an ajax function that calls the controller.
I tried two different controllers; both controllers work but add 2 new records instead of one. See below code snippets:
Button click event in razor view
$('#addLike')
.click(function (e) {
var proposalId = 12;
var url = "#Url.Action("AddLike", "Proposal")/?proposalId=" + proposalId;
$.ajax({
type: "POST",
url: url,
dataType: "json",
traditional: true,
success: function(response) {
window.location.href = actions.common.proposals;
}
});
});
Class model
public class Proposal_Likes
{
public int? Proposal_Id { get; set; }
public int Id { get; set; } (... Identity, DatabaseGenerated)
}
Controller
public ActionResult AddLike(int proposalId)
{
var proposal_Like = new Proposal_Likes
{
Proposal_Id = proposalId
};
UnitOfWork.InsertOrUpdate(proposal_Like);
UnitOfWork.Commit();
return Json("Success");
}
alternative Controller
public ActionResult AddLike(int proposalId)
{
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("addProposalLike", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#propsalId", SqlDbType.Int).Value = proposalId;
con.Open();
cmd.ExecuteNonQuery();
}
}
return Json("Success");
}
I have been working on this for almost 2 days, debugged through the entire code but can't find the cause or a clue where to dig deeper. When I execute the SQL stored procedure manually inside SSMS it does add only one record.
Any help will be appreciated!
Additional info:
No submits, no other buttons on the view
I found the cause:
With my ajax function I was using a parameter in the url.Action in order to pass it to an ActionResult controller:
$.ajax({
type: "POST"
var url = "#Url.Action("AddLike", "Proposal")/?proposalId=" + proposalId;
...
public ActionResult AddLike(int proposalId)
{ ...}
This caused the controller to be called twice.(Why ... I don't know).
When I pass the parameter via the data part of the ajax call
var url = "#Url.Action("AddLike", "Proposal")";
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: {
proposalId: 24,
},
into a model and the controller
public class ProposalViewModel
{
public int proposalId { get; set; }
}
public ActionResult AddLike(ProposalViewModel model)
{ var propId = model.proposalId
...
}
the controller is called only once as expected.

getting null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

Categories

Resources