Javascript - How To Pass Json Collection Object To Mvc Controller Action Method
Dec 21, 2010
I am creating one Json array object and trying to pass it in MVC controller action method but i am getting null paramerter; as per my knowledge json only maps .net primitive datatypes.... so it assign null value.
Note: when i have look at request object i found that there are three parameter of created array. But how to get that value as parameter of function?
I have some textboxes and a table of data created client side that I want pass to a controller as JSON.
I want to use Jquery to enumerate the table.
Assume I have 2 textboxes called name and age. Assume a table with 2 columns. one column with class called phonetype and one column class called phonenumber.
I am trying to send json data from view to controller action. But the issue is the data is not populating in the action parameter List<Score>.
View Model: public class Score { public int QuestionId { get; set; } public int PrevAnswerId { get; set; } public int CurrAnswerId { get; set; } public string CurrAnswerName { get; set; } }
Json Data look like: [ {QuestionId:1, PrevAnswerId:3, CurrAnswerId:3, CurrAnswerName:'Known to Broker'}, {QuestionId:2, PrevAnswerId:7, CurrAnswerId:7, CurrAnswerName:'Completed'}, {QuestionId:3, PrevAnswerId:10, CurrAnswerId:10, CurrAnswerName:'Report'} ]
On window load, I will construct the Json object using "eval()" function and do some operation in the data before its save. On Save Click, I will call the action through the ajax call.
Action: public ActionResult SaveScore(List<Score> score) { // do something... }
But here score comming as collection of 3 elements with zero(for interger property)/null(for string property) values. When I checked in the request I found the data in "parama" property like.
But I am not sure why it is not getting populated in the score list. One full day I spent for this issue but till now I didnt find the solution for this issue.
I have the following javascript. Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null? I checked the javascript and the variable "cnt" is 1 not 2. Why would that be?
[code]
$("#Save").click(function () { var title = $("#recipetitle").val(); var category = $("#category").val(); var preptime = $("#prepTime").val(); var preptimeperiod = $("#lstPrepTime").val(); var cooktime = $("#cookTime").val(); var cooktimeperiod = $("#lstCookTime").val(); var rating = $("#rating").val(); var method = $("#method").val(); var jsontext = '{ "RecipeTitle": "' + title + '",'; jsontext += '"CategoryID":' + category + ','; jsontext += '"PrepTime":' + preptime + ','; jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",'; jsontext += '"CookTime":' + cooktime + ','; jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",'; jsontext += '"Rating":' + rating + ','; jsontext += '"Method":"' + method + '",';....................
I need to use this data as an input to ajax request. For eg. consider a dropdownlist change event, I need to pass these values to the controller.
sample code
//dropdown change event $("#TestReqID").change(function() { var id = 10; var testResults = "abc"; var inXML = "<xml>"; inXML = inXML + "<id>" + id + "</id>"; inXML = inXML + "<value1>" + testResults + "</value1>"; inXML = inXML + "</xml>" $.getJSON("/Home/UpdateTest/Json/" + inXML, function(data) { //success code goes here }); });
in HomeController
public ActionResult UpdateTest(string obj) { if (HttpContext.Request.IsAjaxRequest()) { /* Need to parse data in "obj" from ajax request */ IPTests test = _service.GetIPTest(Convert.ToInt32(id)); return new JsonResult { Data = new { ipTestId = "0", testResults = "" } }; } return View(test); }
instead of xml string is it possible to use javascript object like
I have asp.net mvc application. i want to configure the object in jquery and want to pass it to the the action of controller . where as in my script i am using this for configure data for the ajax call:
[Code]....
it does not calls to action in controller. i think here :
var json = $.toJSON(peform);
is not working as expect. is it need to add any js file to reference ? or mistake in syntax?
I am trying to get this functionality on my jokes website:
www.mysite.com/category/bar
To get all the bar jokes ..etc
The way I have my route right now is:
{controller}/{action}/{id}
which means I have to type:
www.mysite.com/category/index/bar
the problem is that even with that, the string parameter "bar" isn't being acknowledged ! ( I know from debugging). Here is my Index action in the Category controller:
I am trying to return some data as json from an action method.
I have an employee object that looks like this:
public class Employee { public int EmployeeID {get; set;} public string FirstName {get; set;} public string LastName {get; set;} //Other irrelevant properties }
Then I have a view model as follows
public Class EmployeeViewModel { public Employee Supervisor{get; set;} public List<EmployeeViewModel> Employees }
I need to return a json object that looks exactly like this:
For now I only need to go to the second level as above, returning and supervisor and their staff members beneath them.
How would I go about returning this in my action method(I have the viewModel object hydrated already I just need to return it as json). My problem so far has been that the children property does not get populated.
My query is somehow related to passing the id values as parameters in MapRoute on RegisteredRoute method
routes.MapRoute("MachineGroupList:, PhysicalMachine/ListGroupMachine/{used}/Page/{page}", new {controller="PhysicalMachine", action="ListGroupMachine",id="XNA"});
public ActionResult ListGroupMachine(string id, int page=0) { .... }
Everytime I call this Action the Id should be of groupBy column; over here it is 'Used' First time I have called this Action from <%html.ActionLink("Machine","ListGroupMachine", new {id=Model.UsedBy})%> But in my Html.RouteLink the id object is not identified in MapRoute method...
I use the JavaScriptSerializer class of ASP.net to serialize my object and return it to the client side. How can I deserialize the string using JavaScript?
Is it possible to instantiate an HtmlHelper object in a controller action in order to call HtmlHelper.EditorFor?
I would like to call HtmlHelper.EditorFor to return some partial html generated by an editor template in response to an ajax call. If I can do so I would not need to create an ascx file that otherwise would do the call to EditorFor.
I have the following to get the Json abject passed from the controller and populate the various textboxes in the view. However, nothing is happening even though controller is passing a valid Json object. What is wrong with this code?
<script language="javascript" type="text/javascript"> $(document).ready(function() { var url = '<%=Url.Action("DropDownChange") %>'; $("#vendorID").change(function() { var selectedID = $(this).val(); if (selectedID != "New Vendor Id") { //$.post('Url.Action("DropDownChange","Refunds")', function(result) { $.post(url, { dropdownValue: selectedID }, function(result) { alert(selectedID); $("#name").val(result.Name); $("#city").val(result.City); $("#contact").val(result.Contact); $("#address2").val(result.Address2); $("#address1").val(result.Address1); $("#state").val(result.State); $("#zip").val(result.Zip); }); } }); }); This is the code in my controller; public JsonResult DropDownChange(string dropdownValue) // This action method gets called via an ajax request { if (dropdownValue != null && Request.IsAjaxRequest() == true) { paymentApplicationRefund = cPaymentRepository.PayableEntity(dropdownValue); paymentApplicationRefund.Address1.Trim(); paymentApplicationRefund.Address2.Trim(); paymentApplicationRefund.Name.Trim(); paymentApplicationRefund.City.Trim(); paymentApplicationRefund.Contact.Trim(); paymentApplicationRefund.State.Trim(); paymentApplicationRefund.Zip.Trim(); return Json(paymentApplicationRefund,"application/json"); } else { return null; } }
I'm just starting to use the TestHelpers in MvcContrib. I want to try and test an action method on my controller that itself tests if IsAjaxRequest() is true. I've used the same code that is shown in the TestHelper samples to set up the TestControllerBuilder
_controller = new StarsController(); _builder = new TestControllerBuilder(); _builder.InitializeController(_controller);
So that _controller has all the faked/mocked HttpContext inside it, which is really great. But what do I do now to force IsAjaxRequest() on the internally faked Request object to return true?
When I use editurl property in my jqgrid, the controller action gets called after I hit submit button on adding a new row. But how do I get all the grid rows there? Which parameter should I read from my controller action method in order to get the grid data?
I'm using V.S. 2008 and asp.net MVC. I have a form in this page that user selects various items from Select controls. I then construct a string varible that contains each selected element's id a hidden input control that holds this information. How can I pass this variable (and it value of course) to a Controller Action? I am using regular Html Form and the Submit button.
In the following code you see the "ResearchInterests" is the one that holds the string but I can't even reference it in my Controller action, Search. How can I correct this?
Assume the current executing action method is Index() in Home controller. From within Index(), how to obtain the physical file path of the Home controller? Assume we don't know the file structure until runtime.
I am having a dropdown server control on view, when the user clicks the submit btn at that time the form gets posted. and a action method in view controller is called with verb=post.
But the problem is that how should i get reference to the dropdown server control in the action method of view controller?