ASP.NET MVC upload file with ajax with multiple parametrs - json

I need to upload a file from my file input through ajax with multiple parameters through an ASP.NET MVC controller and I am getting an error.
Save file from input to variable data2.
var data2 = new FormData();
var files;
var loadFile = function (event) {
files = $("#upload").get(0).files;
if (files.length > 0) {
data2.append("MyImages", files[0]);
}
};
Send data with ajax
$.ajax({
url: "/Adot/UploadAdopt",
type: "POST",
data: { ForUpload:data2,
Title:"New name"},
success: function (response) {
console.log(response);
}
});
Controller
[HttpPost]
public JsonResult UploadAdopt(HttpPostedFileBase ForUpload, string Title)
{
string path = Path.Combine(Server.MapPath("~/image/adopts"), Path.GetFileName(ForUpload.FileName));
ForUpload.SaveAs(path);
return Json("", JsonRequestBehavior.AllowGet);
}

Related

How to send an array/List with ajax and jquery. Failed to load resource: the server responded with a status of 415 ()

I am new with Jquery Ajax, I am trying to send an array via post. In the following way.
$(function(){
$("#btnSave").click(function(){
var datos = new Array();
$("#imgCurrent tr").each(function () {
var row = $(this);
var id =row.find("td:eq(0)").text();//.html();;
var data=
{
RepositoryCatalogueID: id
}
datos.push(data);
});
var url = "#Url.Action("EditPosition","Carrusel")";
$.ajax({
url: url,
type: 'POST',
contentType: 'json',
data: (datos),
success: function (data) {
$.alert({
icon: "~/Content/Images/success.png",
title: 'Restaurar Imagen',
content: 'RestauraciĆ³n exitosa.',
});
}
})
});
});
An object of this type is received in my controller.
public JsonResult EditPosition([FromBody] IEnumerable<CarruselViewModel> model)
{
bool success = false;
JsonResult jResult;
string message = string.Empty;}
It throws me the error Failed to load resource: the server responded with a status of 415()
And it never enters the controller
you need to cast your data to json. use this :
data: JSON.stringify(datos),
also make sure you put [HttpPost] attribute on top of your action method;
[HttpPost]
public JsonResult EditPosition([FromBody] IEnumerable<CarruselViewModel>
model)
{
bool success = false;
JsonResult jResult;
string message = string.Empty;
}

How to Serialize Model in View and Pass to Controller Action

I have a very specific need to serialize a model in the view and then pass it to a controller action at some point. I can get it to work by doing several hacks but its not pretty.
My test controller action
public ActionResult Index()
{
DefaultOptionValueRound defaultOptionValueRound = new DefaultOptionValueRound()
{
OptionId = 1835,
OptionValueId = 40343
};
TestModel testModel = new TestModel()
{
DefaultOptionValueRound = defaultOptionValueRound
};
return View(testModel);
}
The View
#using Common.Repository.Extensions
#model EngA.SandboxApplication.Controllers.TestModel
#Html.Hidden("DefaultOptionValueRound", Html.Raw(Json.Encode(Model.DefaultOptionValueRound)))
<input type="button" value="submit" onclick="SerializeModelTest.processOptionMag()"/>
<script language="javascript">
SerializeModelTest = {
processOptionMag: function () {
//Testing: This Works
//var defaultOptionValueRound = { OptionId: 1834, OptionValueId: 4034377 }
//var data = JSON.stringify({ defaultOptionValueRound: defaultOptionValueRound });
//This Does Not Work
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = { defaultOptionValueRound: defaultOptionValueRound }; //Stringify Does not work either
$.ajax({
contentType: 'application/json; charset=utf-8',
type: "Post",
cache: false,
url: '#Url.Action("ProcessOptionMag", "SerializeModelTest")',
data: data,
dataType: "json",
traditional: true,
success: function(data) {
alert(data);
}
});
}
}
</script>
The problem is that the serialized model is returned in a stringify form already.
There must be an elegant way of doing this without me have to do JS string manipulation to make it work.
Thank you for your help
I found out that I can un-stringify my result using JSON.Parse and then repackage it with other parameters for sending to the controller.
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = JSON.stringify({ defaultOptionValueRound: JSON.parse(defaultOptionValueRound) });
Now everything works.

unable to Deserializ the form data Error !! Invalid JSON Primitive

I am unable to Deserialized my JASON Serialized FormData
Please review my code
///here its my JSON
$("#btn_pro_spc").click(function () {
var formdata = $("#Product_spec_from").serialize();
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: { formdata : formdata },
datatype:'json',
success: function (data) {
}
});
});
///here it controller
public JsonResult UpdateProductSpecification(string formdata)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
LabCheckingModel LCModel = jss.Deserialize<LabCheckingModel>(formdata);
return Json(jss);
}
I Am getting serialized data perfectly but unable to Deserialized :(
Invalid JSON Primitive
It is not necessary to use use JavaScriptSerializer to deserialize your model. The DefaultModelBinder will do all this for you. Change the script to
$("#btn_pro_spc").click(function () {
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: $("#Product_spec_from").serialize(), // change this
datatype:'json',
success: function (data) {
}
});
});
and change the controller method to
public JsonResult UpdateProductSpecification(LabCheckingModel model)
{
// the value of model will be correctly bound
return return Json(??);
}
Side note: not sure what you are trying to return (currently its an instance of JavaScriptSerializer which does not make sense)

Json Data Not mapped in the backend service

I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});

How to pass a JSON object to an action

I have the following jQuery code in a View in MVC3. I want to load a partial view (named OffshoreECore) in a div (#Form) depending on the JSON object passed in the success function. Here's the code:
var inputParamtrs = { 'HeadId': $('#ExpenseId').val(), MProjid': $('#MProjid').val() };
$.ajax({
type: "POST",
url: "/Expenses/Edit",
data: inputParamtrs,
success: function (json) {
('#Form').load('#Url.Action("OffShoreECore", *What comes here ?!?*)');
}
Thanks.
The second parameter of load() is the data which should be sent to the specified URL along with the request. To send your JSON string, try this:
success: function (json) {
$('#Form').load('#Url.Action("OffShoreECore")', json);
}
You example code is also missing a ' delimiter from the second key in inputParamtrs and the $ from the selector in success, but I guess they're just typos.
$.getJSON("/Expenses/Edit",
{
HeadId: $('#ExpenseId').val(),
MProjid: $('#MProjid').val()
},
function (data) {
elementForResult.innerHTML = data;
});
In Controller:
public JsonResult Edit(int HeadId, int MProjid)
{
...
var result = SerializeControl("~/Views/Expenses/Edit.cshtml", null);
return Json(result, JsonRequestBehavior.AllowGet);
}
private string SerializeControl(string controlPath, object model)
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}