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.
Related
I'm trying to send my data via ajax call to the controller but I check all my code I debug it all values are filled but it continuously shows me this error. event its also show me ON MVC call As Well
The parameters dictionary contains a null entry for parameter 'BrandId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Forms(System.Collections.Generic.IEnumerable1[System.Web.HttpPostedFileBase], System.String, Int32, Int32, Boolean, Int32)'in'AdminDevVersion.Controllers.HomeController'`. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
i have already debugged the code and I have checked if all the values are filled.
My Ajax Code
function uploadSubmitHandler() {
var PName = $("#ProductName").val();
var Category = $("#CategoryDropDown").val();
var Brand = $("#BrandDropDown").val();
var SubCategory = $("#SubCategory").val();
var ProductDescription = $('textarea.textarea-editor').val();
var NewOROldRadio = $("input[name='ProductStatus']:checked").val();
if (state.fileBatch.length !== 0) {
var data = new FormData();
for (var i = 0; i < state.fileBatch.length; i++) {
data.append('files', state.fileBatch[i].file, state.fileBatch[i].fileName);
}
data.append('ProductName', PName);
data.append('CategoryId', Category);
data.append('BrandId', Brand);
data.append('IsNewStatus', NewOROldRadio);
data.append('SubCategoryId', SubCategory);
data.append('Description', ProductDescription);
$.ajax({
type: 'POST',
url: options.ajaxUrl,
data: data,
cache: false,
contentType: false,
processData: false
});
}
}
Controller Code
[HttpPost]
public ActionResult Forms(IEnumerable<HttpPostedFileBase> files, String ProductName, int CategoryId, int BrandId, bool IsNewStatus, int SubCategoryId)
{
List<string> FileNames = new List<string>();
string ImageName = null;
TblProduct InsertProduct = new TblProduct();
if (ModelState.IsValid == true)
{
InsertProduct.Name = ProductName;
InsertProduct.IsActive = IsNewStatus;
InsertProduct.BrdId = BrandId;
InsertProduct.CatId = SubCategoryId;
InsertProduct.Image = ImageName;
InsertProduct.Created = DateTime.Now;
InsertProduct.IsActive = true;
_RepoProduct.Insert(InsertProduct);
_RepoProduct.Save();
TblProRelImg RelatedImages = new TblProRelImg();
foreach (HttpPostedFileBase file in files)
{
string _path = System.IO.Path.Combine(Server.MapPath("~/Content/Images/"), file.FileName);
file.SaveAs(_path);
if (file == files.First())
{
ImageName = file.FileName.ToString();
}
else
{
RelatedImages.PrdID = InsertProduct.ID;
RelatedImages.Image = file.FileName;
_ReporRelatedImages.Insert(RelatedImages);
_ReporRelatedImages.Save();
}
FileNames.Add(file.FileName);
}
ViewBag.CategoryId = Logics.Category();
ViewBag.BrandInfo = new SelectList(DbContext.TblBrands, "Id", "Name");
}
return View();
}
I have expected to send data to the controller
parse your BrandId to int like blow and append to your data
parseInt(Brand)
I am trying to download file through ajax call in asp.net
my javascript:
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
var strAccountCodes = '';
for (var i = 0; i < data.length; i++) {
strAccountCodes += data[i].AccountCode + ",";
}
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes }
});
my action method:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
return File(output, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
code is executing without any errors but it's not downloading any file.
is that anything i am missing?
You should know that AJAX call is not intended to download CSV file directly. Therefore, you can create a byte array from MemoryStream instance and store it inside Session or TempData variable, then return 'successful' state to enable redirect on AJAX success response:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
// creates byte array from stream
TempData["Output"] = output.ToArray();
// returns successful state
return Json("Success", JsonRequestBehavior.AllowGet);
}
Second, create a controller action with GET method and pass stored byte array from Session or TempData into FileResult:
public ActionResult DownloadCSV()
{
// retrieve byte array here
var array = TempData["Output"] as byte[];
if (array != null)
{
return File(array, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
else
{
return new EmptyResult();
}
}
Finally, handle success response to include location.href which will redirect to controller returning FileResult to download CSV file:
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadCSV", "ControllerName")';
}
}
});
As an option, you could pass CSV file name as parameter from AJAX response using query string.
Related issue:
Creating a byte array from a stream
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
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
Im constructing an array of objects like this:
var postData = [];
$.each(selectedFields, function (index, value) {
var testTitle = 'testing ' + index;
postData.push({title: testTitle, title2 : testTitle});
}
I then post it like this(note that i have tried a number of different aproaches):
$.post('SaveTitlesHandler.ashx', { form : postData }, function (data) {
console.log(data);
});
I then try to get the data in a handler...
public class SaveTitlesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string json = context.Request.Form.ToString();
}
}
I cant seem to get proper json out of the request. Anyone got any idea?
cheers.
twD
You are not posting JSON. You are using application/x-www-form-urlencoded. So inside the handler you could access individual values:
public void ProcessRequest(HttpContext context)
{
var title1 = context.Request["form[0][title]"];
var title2 = context.Request["form[0][title2]"];
var title3 = context.Request["form[1][title]"];
var title4 = context.Request["form[1][title2]"];
...
}
If you wanted to POST real JSON you need this:
$.ajax({
url: 'SaveTitlesHandler.ashx',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(postData),
success: function(result) {
console.log(result);
}
});
and then inside the handler read from the request input stream:
public void ProcessRequest(HttpContext context)
{
using (var reader = new StreamReader(context.Request.InputStream))
{
string json = reader.ReadToEnd();
}
}
The JSON.stringify method converts a javascript object into a JSON string and it is a native method built-in modern browsers. You might also need to include json2.js if you want to support older browsers.