Problems updating database with Jquery.Ajax - javascript

I am working on a website and would like to be able to update a field on a database table when a div is clicked. I found some example code right here on stack but for some reason it won't work, even though it was accepted. I am using C# ASP.NET MVC Razor.
My JavaScript function is as follows:
function toggleContent(id, instID) {
var doc = document.getElementsByClassName("messageContent")[id];
$(doc).slideToggle();
$.ajax({
type: 'POST',
url: "#Url.Content('/Messages/MarkSeen/')",
data: {
instanceID : instID
},
dataType: 'json'
});
}
And my JsonResult is as follows:
[HttpPost]
public JsonResult MarkSeen(int instanceID)
{
var markSeen = db.MessageInstances.First(mi => mi.MessageInstanceId == instanceID);
if (markSeen.RegisteredPerson.PersonId == CurrentUser.PersonId)
{
markSeen.Seen = true;
db.SaveChanges();
return Json(true);
}
return Json(false);
}

I'm not sure where your code fails, so I posted complete working code
If you are using the ApiController, please try the following updates to make your code works:
1. add route to WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
2. javascript
$.ajax({
type: "POST",
url: "#Url.Content("/api/lab/MarkSeen")",
data: { "instanceID": instID },
dataType: 'json',
success: function (data) { alert(data)},
error: function () { alert('error'); }
});
3. Add model to match the json from ajax request:
public class labModel
{
public int instanceID { get; set; }
}
4. Controller:
[System.Web.Mvc.HttpPost]
public JsonResult<bool> MarkSeen(labModel data)
{
return Json(true);
}

Related

Return parameter null in controller from ajax

I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}

Ajax POST an object with javascript, but the value in backend is null, why?

So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.

How to make a AJAX GET call in ASP.NET MVC application

I am learning web development. And I just want to make a simple AJAX GET call in ASP.Net MVC Application and I want visualize how it works. But I am not able to do so. I am a beginner and I could have done any silly mistakes. But as of now there are no errors in my code.
Below is what I have:
So, I have a Index.cshtml file which is already loaded. Now in that page I want to make an Ajax GET call to one of the function that I have written in the HomeController and action name is Test. I just want to hit the breakpoint in that Test Action of Homecontroller and return something back to the Success of AJAX Call.
In HomeController I have below Action
[HttpGet]
public ActionResult Test()
{
return View("hello");
}
jQuery
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
}
Confusion: Do I need to create a cshtml for Test. But I actually do not want that. I just want the Test Action to return me one data. And I will display that data in my Already opened Index.csthml file.
Error: No error but I am not able to hit the breakpoint in Test Action of controller. Kindly note that Success of AJAX is hitting but I do not see any data. But I am sure it did not hit the test Action breakpoint.
Change your action method like this
[HttpGet]
public JsonResult Test()
{
return Json("myContent",JsonRequestBehavior.AllowGet);
}
And in your success method in 'html' variable you will get back "myContent".
Example :
function RemoveItem(ItemId) {
if (ItemId && ItemId > 0) {
$.ajax({
cache: false,
url: '#Url.Action("RemoveItem", "Items")',
type: 'POST',
data: { id: ItemId },
success: function (result) {
if (result.success == true) {
$("#CartItemGridDiv").load('#Url.Content("~/User/Items/CartItemGrid")');
alert('Item Removed successfully.');
}
else {
alert('Item not removed.');
}
},
error: function (result) {
alert('Item not removed.');
}
});
}
}
public ActionResult RemoveItem(int id)
{
if (id > 0)
{
bool addToChart = false;
addToChart = Utilities.UtilityClass.RemoveItem(id);
if (addToChart)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult CartItemGrid()
{
List<CartItems> oItemList = (List<CartItems>)Session[MvcMAB.StringConst.CartItemSession];
return View(oItemList);
}
Since you don't want to return a view, you might need to return Json() instead of View()
You need to Allow Get in the action. Like that:
public ActionResult SomeGetAction(int? id)
{
//Some DB query here
var myJsonList = myListQuery;
return Json(myJsonList, JsonRequestBehavior.AllowGet);
}
Or in case of just Simple string response:
public ActionResult SomeGetAction()
{
return Json("My String", JsonRequestBehavior.AllowGet);
}
I would recommend renaming html into response.
Also change that to this in Error Response section.
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (response) {
alert(response);
},
error: function (error) {
$(this).remove();
DisplayError(error.statusText);
}
});
Enjoy.
C#:
public JsonResult Test()
{
return Json("hello");
}
Jquery:
$.ajax({
url: '/Home/Test',
type: 'Post',
dataType: 'json',
success: function (html) {
alert(html);
},
error: function (error) {
alert(error);
}
});

call an Asp Action from javascript

I have a table that will use is populated by javascript when another table option is clicked. All of this works no problem, when I add the delete button to the table the onClick event fires but this isn't ever called in asp.net.
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/',
data:{ id:id }
});
}
please tell me where I've gone wrong.
I have tried
function DeleteLink(id) {
$.ajax({
url: '/PublicPages/LinkDelete/' + id
}
as well
UPDATE:
[HttpPost]
public async Task<IActionResult> LinkDelete(Guid id)
{
var pageId = _linkDataProvider.FindById(id).PublicPage.Id;
_linkDataProvider.Delete(id);
var page = await _pageDataProvider.FindById(pageId);
var viewModel = _pageDataProvider.ConvertToViewModel(page);
return View("Details", viewModel);
}
UPDATE2
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Flooring}/{action=Index}/{id?}");
});
You should specify http method in ajax settings. Try to change your javascript like below:
function DeleteLink(id) {
$.ajax({
type = 'POST',
url: '/PublicPages/LinkDelete/' + id
});
}
Update
If you prefer to use data:{ id:id } then you would need to create a model class:
public class DeleteModel
{
public Guid Id{get;set;}
}
[HttpPost]
public async Task<IActionResult> LinkDelete([FromBody]DeleteModel model)
....

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