How to read serialized data (sent through Jquery POST) in MVC collection - javascript

I have a form and one submit button click, i serialize my form and send it to MVC action.
Jquery code
var formCollection = $('form').serialize();
var path = $(this).attr('data-content-url');
// check if no more error
$.ajax({
type: 'POST',
url: path,
cache: false,
data: { collection: formCollection },
datatype: 'json',
success: function (data) {
// do stuff
}
});
MVC side
[HttpPost]
public ActionResult MethodName( FormCollection collection )
{
}
i do get serialize data in my collection variable as
name=test&id=1 as collection[0]
How can i break this collection[0] so that this name and id can be assigned directly to class parameter, something like
Person p = new person { collection["name"], collection["id"] }
Many thanks

this worked, create a new helper class which convert your serialized data in formcollection as you would normally expect
private FormCollection DeSerialize(FormCollection form)
{
FormCollection collection = new FormCollection();
//un-encode, and add spaces back in
string querystring = Uri.UnescapeDataString(form[0]).Replace("+", " ");
var split = querystring.Split(new [] {'&'}, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, string> items = new Dictionary<string, string>();
foreach (string s in split)
{
string text = s.Substring(0, s.IndexOf("="));
string value = s.Substring(s.IndexOf("=")+1);
if (items.Keys.Contains(text))
items[text] = items[text] + "," + value;
else
items.Add(text, value);
}
foreach (var i in items)
{
collection.Add(i.Key, i.Value);
}
return collection;
}

you need to Deserialize using your model
try this
var response = JsonConvert.DeserializeObject<YourModel>(collection);
var name = response.name ;
var id = response.id;
use foreach loop , to get more records from list

Related

passing an array from ajax call to controller, array empty in controller

Can anyone suggest what I need to change here?
I'm getting classes from elements that contain the class 'changed', the classes I get contain id's that I want to pass to the controller method.
When I look in the network tab I can see the data I want in the payload, it looks like this:
{"list":["GroupId-1","SubGroupId-2","changed"]}
but when I put a breakpoint on the controller the list is null.
This is the class I'm expecting in the controller method:
public class MemberGroups
{
public string GroupId { get; set; }
public string SubGrouId { get; set; }
public string Status { get; set; }
}
javascript for the save
function Savechanges() {
var spans = document.getElementsByClassName("changed");
var list = [];
$.each(spans,
function (key, value) {
$.each(value.classList,
function (key, value) {
list.push(value);
});
});
var dataToPost = JSON.stringify({ list: list });
$.ajax({
url: "/umbraco/Api/OrganisationMemberGroupsDashboardApi/UpdateMemberToGroup",
data: JSON.stringify({ list }),
type: "POST",
contentType: "application/json; charset=utf-8", // specify the content type
})
.done(function (data) {
});
}
controller
public string UpdateMemberToGroup( List<MemberGroups> list)
{
// save records
}
The spans are created dynamically and added to a treeview. When they are dragged and dropped all classes are removed then the 'changed' class is added along with the id classes so I only pass the ones I need to to the controller
var s = document.createElement('span');
s.classList.add('node-facility');
s.classList.add('ui-droppable');
s.classList.add('GroupId-' + value.GroupId);
s.classList.add('SubGroupId-0');
s.id=('GroupId-' + value.GroupId);
s.appendChild(document.createTextNode(value.GroupName));
This variant was tested using postman body json -
["GroupId-1","SubGroupId-2","changed"]
Change your ajax data to this:
data: list,
and your controller action:
public string UpdateMemberToGroup([FromBody] []string list)
{
var memberGroups = new MemberGroups
{
GroupId =list[0],
SubGrouId =list[1],
Status =list[2]
};
// save records
}
This variant was tested in postman using
{"GroupId":"GroupId-1","SubGroupId": "SubGroupId-2", "Status":"changed"}
you can put the code in javascript:
var data={GroupId:list[0],SubGroupId:list[1], Status:list[2]}
......
....
data:data,
.....
your controler action in this case:
public string UpdateMemberToGroup([FromBody] MemberGroups memberGroups)
{
// save records
}
And I don't know what version MVC you use , but for some versions instead of [FromBody] better to use [FromForm] or don't use anything at all.

How to iterate json string which holds array of object in controller

I have converted array of object into json string in jsp as follows
$("#submitButton").click(function(){
var sample = new Array();
var k = 1;
for(var i=0; i < JSONObj.length; i++){
var remarkString = $("#eduRemark"+k).val();
var scoreNum = $("#eduScore"+k).val();
var objectInfo = {"iqrQuestionRemark":remarkString, "iqrQuestionScore":scoreNum,"crtnByUmId":""};
sample.push(objectInfo);
k++;
}
var ArrayData = JSON.stringify(sample);
alert("Json Data:"+ArrayData);
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/Vidyasaarathi/ipusers/submitAssessmentform",
data: ArrayData,
success :function(result) {
}
});
});
The ajax call works fine. At controller side i'm getting list of object as String. in following format
[{"iqrQuestionRemark":"nitin","iqrQuestionScore":"10","crtnByUmId":""},{"iqrQuestionRemark":"akash","iqrQuestionScore":"12","crtnByUmId":""},{"iqrQuestionRemark":"sharad","iqrQuestionScore":"14","crtnByUmId":""}]
Now my question is how to iterate this array of object individually at controller side.
Here is my controller code
#RequestMapping(value={VspCommonConstants.INTERVIEW_PANEL_MANAGER_URL+"/submitAssessmentform"}, method = RequestMethod.POST)
public String submitAssessmentform(#RequestBody List<InterviewQuestionResult> ArrayData,HttpServletRequest request,Model model) throws JsonParseException, JsonMappingException, IOException
{
ObjectMapper mapper = new ObjectMapper();
//String [] actualData = mapper.readValue(ArrayData, String[].class);
//System.out.println("Json converted Data:"+actualData);
System.out.println("Result object:"+ArrayData);
String view = null;
try {
view = "ipsearchForm";
} catch (Exception e) {
model.addAttribute("errormsg", "System is busy...... Please try after some time.");
}
return view;
}
Please suggest some possible way. Here i'm trying to assign json string to 'InterviewQuestionResult' bean which has a getter setter. Thanks in advance.

Get all json key and value from an external json file in MVC with javascript

I am creating a web app in which I have a Json file in which I have many keys with values, like the following,
{
"Login_Header_Text": "Login",
"Login_Header_Recent_Updates": "Recent Updates",
"Login_TextBox_UserName": "User Name",
"Login_TextBox_Password": "Password",
"Login_Button_Login": "Log In",
"Login_ErrorMessage_Usernamerequired": "User name required",
"Login_ErrorMessage_Passwordrequired": "Password required.",
"Login_ErrorMessage_Invalid_Credentials": "Invalid user name/password",
}
and I can retrieve the values like the following
<script>
console.log('#HttpContext.GetGlobalResourceObject("", "Login_TextBox_UserName")');
</script>
now, how can I retrieve whole json file data and print that into my console,
Like, if I have 55 Records in the json file, whole data should be printed in console.log
what is the proper way to do this?
here is how i would do it. in C# and also in javascript
assum we have this js
var json = [{Name: "test", Passowrd:"test" }]
in C# i would convert this to class
public class myjson{
public string Name { get; set;}
public string Password { get; set;}
}
then with reflection call on the property
public GetValue(this myjson o, string propertyName){
return o.GetType().GetProperty(propertyName).GetValue(o);
}
in Jsvascript i would just call this
var value = json[0][property]
I hop this could help you
hello I think this can help you, I made a small example by picking up an answer written in Ajax and writing it in the console.
Look at the function in success, I think that's what you're looking for
function formToJSON(form) {
var obj = {};
var elements = form.querySelectorAll("input, select, textarea");
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
var name = element.name;
var value = element.value;
if (name) {
obj[name] = value;
}
}
return obj;
}
function test(id, url, method) {
var data = formToJSON(document.getElementById(id));
$.ajax({
type: method,
url: url,
data: data,
success: function (output, status, xhr) {
var response = JSON.parse(xhr.responseText);//<--- here is your JSON
for (var item in response) { // and set for to print indivual
console.log(item+' '+response[item]);
}
console.log(response);
},
cache: false
});
}

Binding MVC model in controller which has a complex array

Most of my model is populated using $('form').serializeArray(), however an array of objects that form a paged grid need to be populated from its manager.
For example:
public JsonResult SubmitForm(MyViewModel input)
{
...
public class MyViewModel
{
[Display(Name = "Name")]
public string GridName { get; set; }
[Display(Name = "Description")]
public string GridDescription { get; set; }
public GridRow[] GridRows { get; set; }
The name and description would be picked up by serializeArray(), no issues there. If the GridRow is a string[], then it accepts me simply pushing multiple instances to it into the serialized array that jquery made:
var data = $('form').serializeArray();
for (var i in gridData) {
data.push({ name: 'GridRows', value: gridData[i].id });
}
$.ajax({
type: "POST",
url: '/Central/Results/SubmitForm',
dataType: "json",
data: data,
This way I can at least get an array of the IDs. However, it does not allow me to push the entire object into it (gridData[i]) when I want to populate the proper data type. I always get a null value when it reaches the controller.
Any idea how I need to handle the data in order for MVC to populate the model correctly? Thanks.
I'm pretty sure this is related to having to set the traditional option to true in your Ajax post. jQuery handles arrays a little differently than you'd expect, in terms of when they are posted to MVC controller actions.
So do this:
$.ajax({
type: "POST",
url: '/Central/Results/SubmitForm',
dataType: "json",
traditional: true,
data: data,
...
See this answer for more details.
Turns out just need to add a line and property reference, and add each variable separately.
for (var i in gridData) {
for (var j in gridData[i]) {
data.push({ name: 'GridRows[' + i + '].' + j, value: gridData[i][j] });
}
}
Edit: Just thought I'd post my updated helper method I wrote a while ago for this.
function serializeArray(obj, data, name) {
/// <summary>Turns an object into an MVC standard array of values </summary>
/// <param name="obj" type="Object">Object to serialise (required)</param>
/// <param name="data" type="Array">Array to append data to end of (optional)</param>
/// <param name="name" type="String">Name prefix for all entries (optional/ignore)</param>
if (!data || !(data instanceof Array)) {
data = [];
}
if (obj instanceof Array) {
if (!name) {
throw "Need an object name when converting an array";
}
for (var index = 0; index < obj.length; index++) {
data = serializeArray(obj[index], data, name + '[' + index + ']');
}
} else if (obj instanceof Object) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
data = serializeArray(obj[property], data, name ? (name + '.' + property) : property);
}
}
} else {
data.push({ name: name, value: obj });
}
return data;
}

How tp parse Json result which is returned with an arraylist in a webmethod?

This is a simplified code. I have a webservice (.asmx) as following:
I store some values in Test class and then store the class in an arraylist.
I do this two times in two different arraylists.
and then store these two array lists in a third arraylist.
and then pass this arraylist as output of webmethod.
private class Test
{
public string Id;
public string Name;
}
[webmethod]
public ArrayList RuleReport(long RuleId)
{
Test t = new Test();
t.Id = "1";
t.Name = "a";
ArrayList ar = new ArrayList();
ArrayList ar2 = new ArrayList();
ArrayList ar3 = new ArrayList();
ar.Add(t);
t = new Test();
t.Id = "2";
t.Name = "b";
ar2.Add(t);
ar3.Add(ar);
ar3.Add(ar2);
return ar3;
}
and in js file I want to parse he json result to read each Id and Name values of two arraylists.
id=1,name=a
id=2,name=b
this is my jquery code:
$.ajax(
{ url: " Ajaxes/Rules.asmx/RuleReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: "{'RuleId':'79'}",
async: false,
success: function(data) {
$.each(data.d, function(index, obj) {
alert(obj.d[0].Id);// something like this. How to do it???
})
}, error: function() { }
});
this is the json response in fire bug:
{"d":[[{"Id":"1","Name":"a"}],[{"Id":"2","Name":"b"}]]}
how to get every Id and Name values???
With your current setup inside $.each loop you are getting
[{"Id":"1","Name":"a"}]
as obj. As you can see it's a array of object with only one object as it's content. You can access that object with obj[0] and then their properties can be accessed with obj[0].Id and obj[0].Name
You can do this with the following code
$.each(data.d,function(index,obj){
var id = obj[0].Id;
var name = obj[0].Name;
// do what ever you want with them
})​
Working fiddle

Categories

Resources