Receive a complex object from jquery in mvc controller - javascript

I am trying to submit a object from a form to my mvc controller.
here is the js:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.user = jQuery('#selectUser').val();
model.roleslist = usersRoles;
console.log('model: ' + 'user: ' + model.user + 'roles: ' + model.roleslist);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("
AddUser ")",
dataType: "json",
//data: { model: JSON.stringify(usersRoles) },
data: {
model: JSON.stringify(model)
},
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
now that fetches al the necessary info and builds the object "model" and then posts it to the controller.
Here is my view model:
//for receiving from form
public class submitUserRolesViewModel
{
public string userId { get; set; }
public List<String> rolesList { get; set; }
}
Here is my controller:
//Post/ Roles/AddUser
[HttpPost]
public ActionResult AddUser(StrsubmitUserRolesViewModel model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
How can I receive a json object in the controller? Now currently my model is null when a post is executed by the jquery. This means that it is not binding correctly. I am sure there is just something small wrong here.
Could you please point out where I am going wrong.

jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { alert(data); },
error: function (errMsg) {
alert(errMsg);
}
});

I slightly modified you JQuery and it is working as expected now -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var roles = ["role1", "role2", "role3"];
var rolesArray = jQuery.makeArray(roles);
var model = new Object();
model.userId = 1;
model.rolesList = rolesArray;
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(model),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
Output -

Related

cannot get request from JQuery

I have auto complete input field, so I have done a function to retrieve data based on user request. I have tested the function with webform and it works fine, but when I tried to use api and send request to controller, the controller does not receive any request from JQuery?
JQuery:
$(document).ready(function () {
$("#auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/Employee/GetRe",
data: "{'term':'" + $("#auto").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});
controller:
[HttpGet]
public string GetRe(string term) {
var re = repository.GetCategory(term);
return re.First();
}
function:
[WebMethod]
public string[] GetCategory(string term)
{
List<string> retCategory = new List<string>();
connection();
string query = string.Format("select FirstName from Employee where FirstName Like '%{0}%'", term);
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
retCategory.Add(reader.GetString(0));
}
}
con.Close();
return retCategory.ToArray();
}
}
and it shows this error
"No action was found on the controller 'Employee' that matches the
request ."}
You are formatting your JSON object as a string.
$(document).ready(function () {
$("#auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/Employee/GetRe",
data: {'term': $("#auto").val()},
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});

Jquery Ajax and MVC5 httpPost no value received

I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.

How to get a list from mvc controller to view using jquery ajax

I need to get a list from mvc controller to view using jquery ajax. how can i do that. this is my code. Its alerting error message.
In Controller
public class FoodController : Controller
{
[System.Web.Mvc.HttpPost]
public IList<Food> getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return (FoodList);
}
}
In view
function GetFoodDetails() {
debugger;
$.ajax({
type: "POST",
url: "Food/getFoodDetails",
data: '{userId:"' + Id + '"}',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
Why you use HttpPost for GET-method? And need return JsonResult.
public class FoodController : Controller
{
public JsonResult getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new{ FoodList = FoodList }, JsonRequestBehavior.AllowGet);
}
}
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET",
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
you can do like this , return json data and print it
Read full tutorial : http://www.c-sharpcorner.com/UploadFile/3d39b4/rendering-a-partial-view-and-json-data-using-ajax-in-Asp-Net/
public JsonResult BooksByPublisherId(int id)
{
IEnumerable<BookModel> modelList = new List<BookModel>();
using (DAL.DevelopmentEntities context = new DAL.DevelopmentEntities())
{
var books = context.BOOKs.Where(x => x.PublisherId == id).ToList();
modelList = books.Select(x =>
new BookModel()
{
Title = x.Title,
Author = x.Auther,
Year = x.Year,
Price = x.Price
});
}
return Json(modelList,JsonRequestBehavior.AllowGet);
}
javascript
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("BooksByPublisherId"))",
data: { "id": id },
success: function (data) {
var result = "";
booksDiv.html('');
$.each(data, function (id, book) {
result += '<b>Title : </b>' + book.Title + '<br/>' +
'<b> Author :</b>' + book.Author + '<br/>' +
'<b> Year :</b>' + book.Year + '<br/>' +
'<b> Price :</b>' + book.Price + '<hr/>';
});
booksDiv.html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve books.');
}
});
The reason why i am not getting the result was.. I forgot to add json2.js in the library
public class FoodController : Controller
{
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (FoodList, JsonRequestBehavior.AllowGet);
}
}
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET",
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('eror');
}
});
}
Try This :
View :
[System.Web.Mvc.HttpGet]
public JsonResult getFoodDetails(int? userId)
{
IList<Food> FoodList = new List<Food>();
FoodList = FoodService.getFoodDetails(userId);
return Json (new { Flist = FoodList } , JsonRequestBehavior.AllowGet);
}
Controller :
function GetFoodDetails() {
debugger;
$.ajax({
type: "GET", // make it get request instead //
url: "Food/getFoodDetails",
data: { userId: Id },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
Or if ajax request is creating problems then you can use $.getJSON as :
$.getJSON("Food/getFoodDetails", { userId: Id } , function( data ) {....});
$(document).ready(function () {
var data = new Array();
$.ajax({
url: "list",
type: "Get",
data: JSON.stringify(data),
dataType: 'json',
success: function (data) {
$.each(data, function (index) {
// alert("id= "+data[index].id+" name="+data[index].name);
$('#myTable tbody').append("<tr class='child'><td>" + data[index].id + "</td><td>" + data[index].name + "</td></tr>");
});
},
error: function (msg) { alert(msg); }
});
});
#Controller
public class StudentController
{
#Autowired
StudentService studentService;
#RequestMapping(value= "/list", method= RequestMethod.GET)
#ResponseBody
public List<Student> dispalyPage()
{
return studentService.getAllStudentList();
}
}

Ajax Get Method Error

I have this javascript code, it must get a list of my viewmodel, but success function is not called, error function is called.
What is my error?
var id = 5;
var request = $.ajax({
url: "/ArizaTalep/Get_List?tid=" + id,
type: "POST",
dataType: "json",
data: "{}",
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function (data) { alert("error!!") }
});
Controller:
public List<DURUM_HAREKET_ViewModel> Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return ll;
}
public ActionResult Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return Json(ll, JsonRequestBehavior.AllowGet);
}
Try modifying your action to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return Json(ll);
}
and
var request = $.ajax({
url: "/ArizaTalep/Get_List",
type: "POST",
dataType: "json",
data: {tid: id},
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function (data) { alert("error!!") }
});
Change Controller to:
public ActionResult Get_List(int tid)
{
DH_DataModel dmodel = new DH_DataModel();
var ll = dmodel.GetAll().Where(i => i.T_ID == tid).ToList();
return Json(ll, JsonRequestBehavior.AllowGet);
}
Explanation:
You need to return Json type to get it into your View Success function.

Server side method not getting called

From the below javascript code i am trying to call a serverside method, but serververside method is not getting called. I am using jquery, ajax
<script type="text/javascript" src="JquryLib.js"></script>
<script type="text/javascript" language="javascript">
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var v1 = 'StateId: ' + StateId;
$.ajax(
{
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: '{' + v1 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
</script>
This is my serverside method which i need to call.
private static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
It is giving me the following error: 500 (Internal Server Error)
I cannot figure out what is wrong. please help!
Stack Trace:
[ArgumentException: Unknown web method PopulateCities.Parameter name: methodName]
use this script:
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var data = {
'StateId': StateId
};
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: JSON.stringify(data), // using from JSON.stringify is much better than to try stringify data manually
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and this code for your code behind:
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
Use this script
function GetCities(StateId) {
debugger;
var v1 = "{'StateId': '" + StateId+"'}";
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: v1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and modify Code Behind
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}

Categories

Resources