Passing ViewModel back from controller to Javascript Function MVC - javascript

So I have a ViewModel that holds some basic information, and I am taking in an input from the view. Then the input is sent to a .js function that sends it to a controller function that does some work with it. Right now I am just trying to get the Javascript function to connect and display some irrelevant code on the page just to make sure its connected. I make it through everything with no errors, and at the very end I am returned the errorOnAjax Function, inside of the browser tools, that I have written myself. So there is no problem with any of the code that I can see.
My thought is, I am converting the ViewModel to Json wrong in the controller, in turn, it is returning it the wrong way to the Javascript function and giving the error. If anyone has any suggestions, it would be greatly appreciated!
public class MapInfoViewModel
{
public string Place { get; set; }
public string City { get; set; }
public string State { get; set; }
public string URL { get; set; }
}
And I am getting information from the view via an input box
#using (Html.BeginForm())
{
<input type="text" id="name" />
<button id="myButton" onclick="getInfo()">AJAX</button>
}
This is what my Javascript Function looks like. showInfo is just injecting a basic table into the view with just 1 value inside, just to make sure it is connected.
function getInfo(Info) {
var myInfo = document.getElementById('name').value;
$.ajax({
type: "GET",
dataType: "json",
url: "/CreateRoute/DisplayInfo",
data: { 'myInfo': myInfo },
success: showInfo,
error: errorOnAjax
})
}
and my Controller Function
public ActionResult DisplayInfo()
{
string request = Request.QueryString["myInfo"];
MapInfoViewModel info = new MapInfoViewModel()
{
Place = request
};
return new ContentResult
{
Content = JsonConvert.SerializeObject(info),
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8
};
}

You wrote everything correct code but you just miss the one attribute in view.
you need to mention button type then it will work as per your expectations
<button id="myButton" onclick="getInfo()">AJAX</button>
Now I sharing the complete details of this issue.
Javascript-
function getInfo(Info) {
var myInfo = document.getElementById('name').value;
$.ajax({
type: "GET",
dataType: "json",
url: "/Test/DisplayInfo",
data: { 'myInfo': myInfo },
success: showInfo,
error: errorOnAjax
})
function showInfo(result) {
console.log(result);
}
function errorOnAjax() {
console.log("errorOnAjax");
}
}
View -
#using (#Html.BeginForm())
{
<input type="text" id="name" />
<button type="button" id="myButton" onclick="getInfo()">AJAX</button>
}
Controller-
public ActionResult DisplayInfo()
{
string request = Request.QueryString["myInfo"];
MapInfoViewModel info = new MapInfoViewModel()
{
Place = request
};
return new ContentResult
{
Content = JsonConvert.SerializeObject(info),
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8
};
}

First return with json in controller.
public ActionResult DisplayInfo(string myInfo)
{
MapInfoViewModel info = new MapInfoViewModel()
{
Place = myInfo
};
return Json(info,JsonRequestBehavior.AllowGet);
}
In Front End use ajax like this.
$( "#myButton" ).click(function() {
let data={myInfo:$('#name').val();};
$.ajax({
type: "GET",
dataType: "json",
url: "/CreateRoute/DisplayInfo",
data: data,
success: function (response){
//do
},
error: function (error){
}
});
});

You need to create JsonResult function, then return Json(info, JsonRequestBehavior.AllowGet) as #sadullah zolfqar answered you.
Please refer to the below link to get the full explanation:
https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/

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
}
})

Viewmodel contents null after ajax call?

I am creating an ASP.NET MVC application. I am currently developing a search page where both the search box and the table of results are displayed on the same page. To do this I have used Partial Views and AJAX/JSON calls with a viewmodel. After entering the two search terms in the textbox, both are null in the controller after being passed through ajax.
Here is the code:
ViewModel:
public class ExampleViewModel
{
public string search { get; set; }
public string search2 { get; set; }
}
Controller:
[HttpPost]
public ActionResult Search(ExampleViewModel searchTerm)
{
var searchList = db.UserLists.Where(x => x.LastName.Contains(searchTerm.search));
return PartialView("_SearchResultsPartial", searchList);
}
Body of Index View:
<body>
<div>
#Html.TextBoxFor(model => model.search)
#Html.TextBoxFor(model => model.search2)
<input type="submit" value="Search" onclick="return getSearchResults()"/>
</div>
<div id="search-results">
</div>
<script>
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
function getSearchResults() {
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
</script>
Again, after setting a breakpoint on the Search [POST] method, the ExampleViewModel's terms are null.
At first sight, it seems that you have to retrieve the values within the function scope:
function getSearchResults() {
//Read these values on button click
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
Otherwise, the exViewModel is just determined on page load.

Pass json data from Google Maps to MVC controller with AJAX

I want to store data about addresses and coordinates of markers on map, so I'm creating button in Infowindow which will redirect me to form on another view (also with another controller). I want this form to be already filled with data about coordinates and address. I have function called on button click with AJAX code in it to send JSON data to method in controller. Problem is that after clicking on button controller method isn't called (although function call works properly while debugging). I've been searching a lot for a solution, but I really don't know what did I do wrong.
Call to addMarker:
google.maps.event.addListener(marker, 'click', function (event) {
if(infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: data});
infowindow.open(map, marker);
var buttonAdd = document.getElementById('addButton');
buttonAdd.onclick = function() {
addMarker(event.latLng, address);
}
});
JS function with AJAX:
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress + location) //it's ok, i checked with firebug
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data
})
}
Controller:
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
For now I'm just trying to get to another view without doing anything with recieved data, but it's not working. There's definetely something wrong with ajax or controller. I'm new to MVC, JS and AJAX, so please forgive me if it's something stupid. Thanks in advance.
TL;DR - Clicking on button should result in recieving another view with partially filled (with address and coordinates) form.
Found the problem.
You are using dataType: "json". If you want to post JSON in MVC then you need to create appropriate model with the same format that you are going to post.
Take a look at below example.
Controller :
public class JsonPostExampleController : Controller
{
[HttpPost]
public ActionResult JsonPost(JsonModel data)
{
return View();
}
}
Javascript :
$.ajax({
type: "POST",
url: "JsonPostExample/JsonPost",
dataType: 'json',
data: { 'name': 'ravi' },
success: function (data) { }
});
Model :
public class JsonModel
{
public string name { get; set; }
}
Now as per your requirement, we can not use dataType: "json" as you can't create model according to google's response format for fulladdress and location.
So you need to use dataType: "text" and for that you only need to modify your javascript.
Update your javascript block with below :
function addMarker(location, fulladdress) {
var data = JSON.stringify(fulladdress) + JSON.stringify(location)
$.ajax({
type: "POST",
url: "Incidents/Create",
dataType: "text",
data: { JsonStr : data }
});
}
and your controller code remains same as :
public class IncidentsController : Controller
{
//some code
[HttpPost]
public ActionResult Create(string JsonStr)
{
return View();
}
//some code
}
now you should be able to get your data in string format at server side. If you want JSON server side then you can parse the string.

Problems updating database with Jquery.Ajax

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);
}

Categories

Resources