How do I access parameters of my POST request within a controller - c#

Javascript:
$.post("/DataAPI/messageProcessor", { query: "Hello World!" }, function (data) {
Handle(data);
}
});
Controller:
[System.Web.Http.AcceptVerbs("Post")]
[System.Web.Http.ActionName("messageProcessor")]
public ResponseModel messageProcessor(string query)
{
ResponseModel model=DoStuff(query);
return model;
}
How do I access query from the controller. It always arrives as query == null. There is Request object available too but I am not sure how to navigate through its members to reach my "Hellow World!".

You need to pass name-value pairs from the client:
$.post("/DataAPI/messageProcessor"
, { query: "Hello World!" }
, function (data) {} );
Check jQuery.Post for more details.

try this :
$.post("/DataAPI/messageProcessor", { 'query' : 'Hello World!' }, function (data) {
Handle(data);
}
});

Thanks to a coworker. Solution is as following:
public class QueryClass
{
public string query { get; set; }
}
public ResponseModel messageProcessor(QueryClass query)
{
ResponseModel model=DoStuff(query.query);
return model;
}

Related

How do I send a JavaScript array to a controller in a .net core 3.1 application?

The javascript side of things looks like this:
var self = this;
self.services = ko.observableArray([]);
self.saveServices = function () {
if (self.services().length > 0) {
var obj = JSON.stringify({ services: self.services() });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: '/Business/SaveServices',
data: obj,
success: function (data) {
$("#saveModal").modal('show');
if (!data) {
$("#saveDetails").text('Processing error, please try again or email us.');
return;
} else if (data === "saved") {
$("#saveDetails").text('Saved changes.');
setTimeout(function () {
$('#saveModal').modal('hide');
}, 2500);
} else {
$("#saveDetails").text(data);
}
},
error: function (error) {
$("#saveModal").modal('show');
$("#saveDetails").text('Processing error, please try again or email us.');
}
});
}
}
Then my controller looks like this:
[HttpPost]
public async Task<JsonResult> SaveServices([FromBody]SaveServicesRequest saveServicesRequest)
{
try
{
if (User.Identity.IsAuthenticated)
{
return Json("saved");
}
return Json("User is not authenticated.");
}
catch (Exception ex)
{
logger.Error(ex + ". Users Email address: " + User.Identity.Name);
return Json("Processing error, please try again or email us.");
}
}
public class SaveServicesRequest
{
public List<services> services { get; } = new List<services>();
}
public class services
{
public string service { get; set; }
}
Am hitting the controller but the array of items I'm expecting is not returned (saveServicesRequest is empty), I cannot seem to pass an array in any form. Anyone see what am doing wrong? The data/json is being sent client side, think the problem might lie in how am building the json and receiving it.
The problem is that you're initializing services to a new list in SaveServicesRequest. The properties should also have public getters and setters for model binding.
Try updating your class to:
public class SaveServicesRequest
{
public List<services> services { get; set; }
}

Sending n number of parameters in api (aspnet core)

I am trying to call an Web API which is in aspnet core
Problem is , the number of parameters are not fixed in this. Parameter can be 2 or 10 ( no of parameters will be between 0 to 15 , a guess )
Below is JS code
$(function () {
$('#btn').click(function () {
var src = [
{
"Question1": "Answer1",
"Question2": "Answer2",
"Question3": "Answer3",
"Question4": "Answer4",
"Question5": "Answer5"
}
];
$.ajax(
{
url: 'api/Default/',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(src),
contentType: "application/json",
success: function (d) {
alert("Success");
},
error: function (e) {
alert("Error please try again");
}
});
})
})
And API
[Produces("application/json")]
[Route("api/Default/")]
public class DefaultController : Controller
{
[HttpPost]
public JsonResult apc(string [][] s)
{
string str;
//Code Here
return Json(true);
}
}
I also tried adding a list of class as parameter instead of string array
public class param
{
public string key { get; set; }
public string Value { get; set; }
}
But Parameter value is always null.
I used the same concept in MVC5 and it works perfectly there but not working in .Net Core
How can we send multiple parameter here ??
Because of the dynamic nature of the data to be posted you can use an array of Dictionary
[Produces("application/json")]
[Route("api/Default/")]
public class DefaultController : Controller {
[HttpPost]
public JsonResult apc([FromBody]Dictionary<string,string>[] data) {
var value = data[0]["Question1"]; // Should be "Answer1"
//Code Here
return Json(true);
}
}
Try to send the JSON as string and send it like bellow :
[HttpPost]
public JsonResult apc(string s)
{
string str;
//Code Here
return Json(true);
}
then handle the json from the .NET side

pass query results to ajax callback

I am making a live search, where a user types something inside a text box and then via ajax results are fetched and added to a ul and in this specific case I am looking for usernames, so if a username is johnny and the user types in jo then johnny should come up and so on.
I have the ajax js code, a post method and a list model view of users, I am now trying to return the list but doesn't seem to be working.
my js:
$("input#searchtext").keyup(function (e) {
var searchVal = $("input#searchtext").val();
var url = "/profile/LiveSearch";
$.post(url, { searchVal: searchVal }, function (data) {
console.log(data);
});
});
LiveSearch view model
public class LiveSearchUserVM
{
public LiveSearchUserVM()
{
}
public LiveSearchUserVM(UserDTO row)
{
FirstName = row.FirstName;
LastName = row.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
the post method
[HttpPost]
public List<string[]> LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return usernames;
}
So basically I want to return a list (or something else) of columns that contain a specific string, and pass all the results to javascript thru ajax callback.
To return the result as JSON alter your method to the following:
[HttpPost]
public JsonResult LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return Json(usernames);
}
you can use like this . The idea is to use success funtion
$.ajax({
url : ""/profile/LiveSearch"",
type: "POST",
data : searchVal ,
success: function(data)
{
//data - response from server
},
error: function ()
{
}
});
and return JsonResult from Post method

Cannot implicitly convert type - missing cast - models.views

I am having trouble building this code - I have an api controller which gets its data from the service layer via the models and this is what i have:
api controller
public class RoleApiController : ApiController
{
private RoleService _roleService = new RoleService();
public RoleUser GetRoleUser(int sectionID)
{
if (sectionID != null)
{
return _roleService.GetUsers(sectionID);
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
Model
public partial class RoleView
{
public RoleView()
{
this.Users = new HashSet<RoleUser>();
}
public ICollection<RoleUser> Users { get; set; }
}
public class RoleUser
{
public string Name { get; set; }
public string Email { get; set; }
}
ERROR MESSAGE:
Cannot implicitly convert type System.Collections.Generic.IEnumberable<...RoleUser> to RoleUser. An explicit conversion exists(missing a cast?)
for this line: return _roleService.GetUsers(sectionID);
JavaScript
<div>
Name: <span id="name"></span>
</div>
<div>
Email: <span id="email"></span>
</div>
<script type ="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type ="text/javascript">
getRoleUser(9, function (roleUser) {
$("#name").html(roleUser.Name);
$("#email").html(roleUser.Email);
});
function getRoleUser(id, callback) {
$.ajax({
url: "/api/RoleUser",
data: { id: id },
type: "GET",
contentType: "application/json;charset=utf-8",
statusCod: {
200: function (roleUser) { callback(roleUser); },
404: function () { alter("Not Found!"); }
}
success: function(result){
result.each(function())
}
});
}
</script>
Umm your returning a collection of users when you should be returning just one? I can't really tell whether you actually want a collection or not from the code you've shown, but that is your issue.
This will let your code compile, but may not be the solution you want:
return _roleService.GetUsers(sectionID).FirstOrDefault();
Your method declaration says it returns RoleUser (singular) while your method would hint it returns a collection. So either you need to fix the method to return a list or return only a single result from your GetUsers method.

What is the use case for using a JsonResult action in asp.net mvc3?

When is it typical to use the JsonResult action in an ASP.NET MVC 3 application?
From where is the JsonResult usually called; from another action or an actionlink rendered in the html?
Can you give me some examples where you want json instead of a typical view?
Say, for example you wanted to populate a jQuery autocomplete with a list of values based on a selection of another field, so you can't determine the data on page load. I would typically call an action method in a $.ajax call, then return an array of items to populate the autocomplete with.
Example, here's my jQuery, one function for the call and another that gets called to populate the automcomplete with received data:
$(function() {
$.ajax({
url: '#Url.Action("GetHomes", "Account")',
type: "POST",
datatype: "json",
success: function (data) {
if (data.Success || data.Success == null) {
WireUpHomesData(data);
} else {
ShowErrorDialog();
}
}
});
ShowDialog();
});
function WireUpHomesData(data) {
var homes = new Array();
for (var i = 0; i < data.length; i++) {
homes[i] = { label: data[i].HomeName, text: data[i].HomeId, icon: data[i].HomeIcon, desc:data[i].HomeAddress };
}
$("#home").autocomplete({
source: homes,
select: function (event, item) {
homeUrl = '#Url.Action("Site", "Sites")/' + item.item.text;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><span class='" + item.icon + "'/><span class='fs-ui-autocomplete-home'>" + item.value + "</span><br>" + item.desc+ "</a>")
.appendTo(ul);
};
$(".ui-autocomplete").addClass("fs-ui-autocomplete");
}
And here is my controller:
public JsonResult GetHomes()
{
return Json(RequiresAclAttribute.HomesForUser());
}
And here's the method signature for the method that's called:
public IEnumerable<HomeInfo> HomesForUser()
And for clarity, here's the HomeInfo class:
public class HomeInfo
{
public string HomeId { get; set; }
public string HomeName { get; set; }
public string DisplayName { get; set; }
public string HomeAddress { get; set; }
public string HomeIcon { get; set; }
}
JsonResult is a subclass derived from ActionResult class. You can use this when you want to return a Json object.
public JsonResult GetItems()
{
var jsonResult=new { Id = "23", Name = "Scott"};
return Json(jsonResult,JsonBehaviour.AllowGet);
}
This will return the same result as
public ActionResult GetItems()
{
var jsonResult=new { Id = "23", Name = "Scott"};
return Json(jsonResult,JsonBehaviour.AllowGet);
}
Possible use of this is to get some chunk of data in asynchronous way. Ex : Imagine you have a drop down where you are showing the states and when user selects a state, you want to to bring the list of cities belongs to the state and show it in the page without a page refrest. you can call use jQuery ajax /getJson method (short hand of jQuery get with json as datatype) method to get this data from an ActionMethod which returns Json data.
A small example to call an Action method which returns the Json data
$(function(){
$.getJSON('YourController/GetItems', function(data) {
alert(data.Id);
alert(data.Name );
});
});
With JsonResult class the response content type will be "application/json" if nothing is specified explicitly. Internally The ExecuteResult method uses JavaScriptSerializer to Serialize the content when returning data.
The JsonResult is very usefull wehn making ajax calls from javascript, e.g. using getJSON from jQuery: http://api.jquery.com/jQuery.getJSON/
The benefit of JsonResult is it returns a JSON formatted result without effort.
An Ajax request from a client script that does not involve a full page load. Basically.
Whenever there is client side processing and client need that data use jsonresult like in autofill or remote validation

Categories

Resources