MVC: Ajax POST removes backslash - javascript

I'm currently trying to use ajax to post a string to a controller action, however, for some reason the backslash in my string is removed when the my controller action receives the data.
view.cshtml
This is what I pass from my Razor view to JS
// Model.BookTitle = "Peter Rabbit \1234"
var book = {
title: '#HttpUtility.JavaScriptStringEncode(Model.BookTitle)',
}
JavaScript
function saveBookTitle(){
$.ajax({
url: '/home/savebooktitle',
type: 'POST',
data: { bookTitle: book.title },
success: function (data) {
alert('saved');
}
})
}
Controller
[HttpPost]
public ActionResult SaveBookTitle(string bookTitle)
{
// do stuff
}
The data I receive at the SaveBookTitle action is "Peter Rabbit 1234". Not sure what I'm doing wrong. Any help would be greatly appreciated.

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.

How to call a cs function in another library with ajax

Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}

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!

Ajax data not getting to controller? why?

I am working with mvc4 application. I developed a form using .cshtml file, which inherits the model and has its corresponding controller action.
I am submitting the form using a ajax jquery like,
var body=$('#formId').serialize();
$.ajax({
url: submitAction,
type: "POST",
datatype: "json",
data: body,
success: function (data) {
if (data != null) {
alert("success");
}
});
"body" is fine and it has serialized data and the submitAction is the var which holds my controller action and the controll is transfered there.
EDIT:
My controller looks like,
public JsonResult(ParentModel model) /*here model always hold null values, WHY??*/
{
//stmts..
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
But, there the parameter of my controller action is showing null values. Can someone tell what could be the mistake and how can I resolve it?
$.ajax({
url: submitAction,
type: "POST", <-- you make post, but asp.net mvc controller receives default GET request
data: { model: body},
[HttpPost]
public JsonResult(string model) //<--now you pass string and to Deserialize in ParentModel
{
JavaScriptSerializer jss= new JavaScriptSerializer();
ParentModel pmodel = jss.Deserialize<ParentModel >(model);
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
Try edit data: section in you request,
remove datatype: "json"
And edit type model parameter to string

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