Post jqgrid data to mvc3 controller - asp.net-mvc-3

How should I post the data entered in a jqgrid plugin to a MVC3 controller?
Thanks In Advance
Some code
Sending data to mvc3 controller
var lineas = $("#articulosIngresadosTable").getRowData();
var model = {
ObraSocialId: $("#idObraSocialTextBox").val(),
Lineas: lineas
};
$.ajax({
type: 'POST',
url: '#Url.Action("Nueva", "Factura")',
data: model,
success: function (data) { alert(JSON.stringify(data)); },
dataType: "json"
});
The controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Nueva(FacturaNuevaModel model)
{
return Json(model);
}
The model
public class FacturaNuevaModel
{
public string ObraSocialId { get; set; }
public IList<Linea> Lineas { get; set; }
What I can't undestand is that I'm sending the same Json with Poster and works, but not whit jquery from the view
Using the post from the view, ObraSocialId is populated in the controller, and the Lineas collection have the items, but every property in Linea has a null value

The problem was the contentType ...
Here is the working code
var lineas = $("#articulosIngresadosTable").getRowData();
var model = {
ObraSocialId: $("#idObraSocialTextBox").val(),
Lineas: lineas
};
var modelString = JSON.stringify(model);
$.ajax({
type: 'POST',
url: '#Url.Action("Nueva", "Factura")',
data: modelString,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) { alert(JSON.stringify(data)); }
});

Related

How to pass the input file type to ASP.NET Core 3.1 MVC using ajax with traditional?

How to pass the input file type to ASP.NET Core 3.1 MVC using ajax with traditional below?
const _f = JSON.stringify({
data: {
users_pid : xusers_pid,
avatar: {
file: document.getElementById('avatar_logo').files[0]
}
}
});
$.ajax({
type: 'POST',
url: '/User/Update/',
traditional: true,
data: _f,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
showSuccess(result.message);
},
error: function (result) {
showError(result.message);
}
});
[HttpPost]
[Route("/User/Update")]
public JsonResult Update_Data([FromBody] JObject _jo)
{ }
I don't know how to pass the value of input file type (in my case is avatar_logo) to ASP.NET Core 3.1 MVC?
If you want to pass a file to action with ajax,you can try to use FormData.Here is a working demo:
Models:
public class FileModel{
public string users_pid { get; set; }
public Avatar avatar { get; set; }
}
public class Avatar {
public IFormFile file { get; set; }
}
View:
<input id="theFile" type="file" />
<input id="xusers_pid" />
<button onclick="PostFile()">
submit
</button>
js:
function PostFile() {
var formData = new FormData();
formData.append('avatar.file', $('#theFile').get(0).files[0]);
formData.append('users_pid', $("#xusers_pid").val());
$.ajax({
type: "POST",
url: "/User/Update/",
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
});
}
action:
[HttpPost]
[Route("/User/Update")]
public JsonResult Update_Data(FileModel fileModel)
{
return new JsonResult("s");
}
result:

Passing two different list from controller to view through Ajax Success in MVC

Is there any way to pass two different list from controller to view using ajax success.
My Ajax Code is
$.ajax({
url: "#Url.Action("GetDoctorWiseReport","DCDReport")",
data: { fromDate: fromDate, toDate: toDate },
type: "post",
datatype: "json",
success: function (data) {
// do something
}
My Controller Code is
public JsonResult GetDoctorwiseReport(DateTime fromDate,DateTime toDate)
{
IEnumerable<DoctorVM> Doctors = homeObj.GetDistinctDoctorsFromTransactionMaster(fromDate, toDate);
IEnumerable<WorkOrderDetailsVM> woDetails = homeObj.GetDoctorwiseReport(fromDate, toDate);
return Json(woDetails.ToList());
}
I want to pass both Doctors and WoDetails through Json.
As Stephen Muecke said
return Json(new { x = woDetails, y = Doctors });
This works fine.

Pass List from view to controller

i am trying to pass List from view to controller but i am getting null value. code is written as follows :
model class :
public class testModel
{
public int ID { get; set; }
public string Name { get; set; }
public List<myModel> ParameterList {get;set;}
}
jquery and ajax code to post data to controller :
var myModel = {
"Name":"test",
"Description":"desc"
};
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: JSON.stringify(Object),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
i am getting value for Name property but not for ParameterList.
What is wrong here ? am i missing anything ?
Please help me out.
Thanks
Edit : Controller Code from comments,
public JsonResult Save(Object Obj)
{
// logic for managing model and db save
}
You said,
I am getting value for Name property but not for ParameterList.
Which makes me wonder what is the structure of myModel, as you have declared ParameterList as a list of myModel type : List<myModel> ParameterList
Also I would recommend you to log JSON.stringify(Object) to console and check the Json value you are actually posting to the controller.
Here is what I found you must be posting back
{"Name":"yasser","ParameterList":{"Name":"test","Description":"desc"}}
Also read these articles :
How can I pass complex json object view to controller in ASP.net MVC
Pass JSON object from Javascript code to MVC controller
Try this:
var myModel = [{
"Name":"test",
"Description":"desc"
}];
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: Object,
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
Just try like this..Hope this would help!!
script:
var emp = [{ 'empid': 1, 'name': 'sasi' },{ 'empid': 2, 'name': 'sathish'}];
emp = JSON.stringify(emp)
$.post("/Home/getemplist/", { 'emp': emp })
Controller:
Here i just changed the parameter to string type. using JavaScriptSerializer you can able to convert this string data to your class list objects.. you can understand it better if u see my code below:
public void getemplist(string emp)
{
List<Emp> personData;
JavaScriptSerializer jss = new JavaScriptSerializer();
personData = jss.Deserialize<List<Emp>>(emp);
// DO YOUR OPERATION ON LIST OBJECT
}

Nested models don't bind

I want to pass a JSON data structure to an MVC (3) Controller, have the JSON object be translated into a C# object, with all properties bound. One of the properties is a simple Type. That's basic model binding, right?
Here are my models:
public class Person
{
public string Name { get; set; }
public JobTitle JobTitle { get; set; }
}
public class JobTitle
{
public string Title { get; set; }
public bool IsSenior { get; set; }
}
Here is my Index.cshtml page (which makes an AJAX request, passing in a JSON object which matches the strcture of the "Person" class):
<div id="myDiv" style="border:1px solid #F00"></div>
<script type="text/javascript">
var person = {
Name: "Bob Smith",
JobTitle: {
Title: "Developer",
IsSenior: true
}
};
$.ajax({
url: "#Url.Action("ShowPerson", "Home")",
data: $.param(person),
success: function (response){
$("#myDiv").html(response);
},
error: function (xhr) {
$("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
}
});
</script>
And my HomeController looks like this:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ShowPerson(Person person)
{
return View(person);
}
}
Ignore the "ShowPerson.cshtml" file for now because the problem occurs before that is ever needed.
In the HomeController.ShowPerson action, the "person.Name" property is correctly bound and the "person.JobTitle" object (containing "Title" and "IsSenior" properties) is instantiated but still has the default values of "Title = null" and "IsSenior = false".
I'm sure I have done nested model binding without problem in the past. What am I missing? Can anybody shed any light on why model binding only seems to work one level deep?
I've searched SO, and it seems everybody else is having binding problems when sending data from forms, so maybe I'm missing something in my $.ajax() request?
ok, there are couple of changes you need to do,
Set dataType as json
Set the contentType as application/json; charset=utf-8.
Use JSON.stringify()
below is the modified code. (tested)
var person = {
Name: "Bob Smith",
JobTitle: {
Title: "Developer",
IsSenior: true
}
};
var jsonData = JSON.stringify(person);
$.ajax({
url: "#Url.Action("ShowPerson", "Home")",
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (response){
$("#myDiv").html(response);
},
error: function (xhr) {
$("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
}
});
Add the content type to the ajax
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
data: $.toJSON(person);

MVC3 jquery ajax parameter data is null at controller

I have a controller action that I want to update via a jquery call. The action runs, but there is no data in the parameters.
I am using a kedoui grid with a custom command in a column that I want to run some server code.
kendoui grid in view
...
columns.Command(command =>
{
command.Custom("ToggleRole").Click("toggleRole");
});
...
The model is of type List<_AdministrationUsers>.
public class _AdministrationUsers
{
[Key]
[ScaffoldColumn(false)]
public Guid UserID { get; set; }
public string UserName { get; set; }
public string Role { get; set; }
}
Here is my toggleRole Script:
<script type="text/javascript">
function toggleRole(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
alert(JSON.stringify(dataItem));
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
}
</script>
Here is my controller action:
[HttpPost]
public ActionResult ToggleRole(string UserID, string UserName, string Role)
{
...
}
The controller action fires, but there is no data in any of the parameters.
I put the alert in the javascript to verify that there is indeed data in the "dataItem" variable. Here is what the alert text looks like:
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Did you try specifying the dataType and contentType in you ajax post ?
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
It looks like you are posting the whole object as one Json string, while the controller expects three strings. If you are using MVC3 the parameter names also have to match the controllers signature. Try to parse up your data object so that it matches the input expected from the controller. Something like this:
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: { UserID: dataItem.UserID, UserName: dataItem.UserID, Role: dataItem.Role },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
Hope that helps!
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Seems incorrect to me. Wouldn't you want this?
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role" : "Admin"}
Notice the "Role" : "Admin"

Resources