Send Uploading Files Together With Form Data - c#

var formData = new FormData($("form#neweventform")[0]);
$.ajax({
url: "/Event/NewEvent",
type: "POST",
data: formData,//JSON.stringify(saveEventModel),
async: false,
dataType: 'json',
//contentType: 'application/json; charset=utf-8',
cache: false,
contentType: false,
processData: false,
fail: function (r) {
alert('error.');
},
success: function (result) {
}
...
On the controller side I have:
public JsonResult NewEvent(EventModel saveEventModel, List<HttpPostedFileBase> files)
{
}
I receive file in List<HttpPostedFileBase> files object but it's null. May be data is not posted to the server?
I think I'm doing something wrong conceptually. :/
How to upload images together with other form data like name, date, address etc.?..

Is this what you're looking for?
C# MVC controller
public class UploadController : Controller
{
[HttpPost]
public JsonResult FilesList(List<HttpPostedFileBase> myFiles)
{
string message;
if (myFiles == null)
{
message = "myFiles is null";
}
else if (myFiles.Count != 2)
{
message = "myFiles.Count is " + myFiles.Count;
}
else
{
message = string.Format("myFiles[0] is {0}, myFiles[1] = {1}",
myFiles[0] == null ? "null" : myFiles[0].FileName,
myFiles[1] == null ? "null" : myFiles[1].FileName);
}
return Json(new
{
Message = message
});
}
}
HTML + Javascript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload Demo </title>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function ()
{
$('#sendButton').click(function ()
{
var form = $('#myForm')[0];
var formData = new FormData(form);
$.ajax({
data: formData,
processData: false,
contentType: false,
dataType: 'json',
type: 'POST',
url: 'Upload/FilesList',
error: function (jqXHR, textStatus, errorThrown)
{
alert('failure\n' + textStatus);
},
success: function (data, textStatus, jqXHR)
{
alert(data.Message);
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
File 1: <input type="file" name="myFiles" /><br />
File 2: <input type="file" name="myFiles" />
</form>
<button id="sendButton">Submit over AJAX</button>
</body>
</html>

Related

Ajax call to call a Controller give 404 error

I am using Ajax call to call a Controller method but I am getting this error:
http://localhost:55942/%22GetCalculateAmortizationSchedule%22,%20%22Home%22 404 (Not Found)
This is my Controller method:
[HttpPost]
public ActionResult GetCalculateAmortizationSchedule()
{
var data = ......
var httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync("http://localhost:62815/v1/APR/CalculateAmortizationSchedule", data).Result;
var returnValue = response.Content.ReadAsAsync<Dictionary<int, AmItem>>().Result;
return Content(returnValue.ToString());
}
This is the View code:
<form id="MyForm" method="post">
....
<input type="submit" id="test" value="test" />
</form>
and this is the Ajax code:
$('#MyForm').submit(function (e) {
$.ajax({
url: '#Url.Action("GetCalculateAmortizationSchedule", "Home")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
contentType: false,
processData: false,
success: function (result) {
alert("success");
console.log(result.data);
// here in result you will get your data
},
error: function (result) {
}
});
e.preventDefault();
});
I think problem is this line that cannot find the url:
url: '#Url.Action("GetCalculateAmortizationSchedule", "Home")',
Use this instead of URl
url: "/home/GetCalculateAmortizationSchedule"
If you on same controller then do not need to add controller name
url: '#Url.Action("GetCalculateAmortizationSchedule")',

How to append JSON data into select tag in ajax javascript

I am developing an ASP.Net MVC5 project and I am calling a webservice in my project with ajax. Every thing is ok so far and at the end the city names can be appended into the select tag, but the code below doesn't work:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function f1() {
var token="";
$.ajax({
data: { webservice_username: 'webservice_usernam', password: 'password' },
url: 'http://www.travelinsure.ir/api/v1.1/authenticate',
type: 'POST',
dataType: 'json',
success: function (data) {
$.each(data, function (idx, result) {
token = result;
f2(result);
})
},
error: function (x, y, z) {
alert(x.responseText);
alert(z);
}
});
}
function f2(token) {
// alert('New: '+token);
$.ajax({
data: { token: token },
url: 'http://www.travelinsure.ir/api/v1.1/getcitylist?token=',
type: 'GET',
dataType: 'json',
success: function (data) {
results = JSON.stringify(data);
// a = JSON.parse(data);
alert(results);
a = $.parseJSON(data);
alert(a);
$.each(data, function (idx, r) {
$("#sel").append("<option value='" + r.city_id + "'>'" + r.city_name + "'</option>");
alert(result.city_name);
})
},
error: function (x, y, z) {
alert(x.responseText);
alert(z);
}
});
}
</script>
</head>
<body>
<div>
<input type="submit" name="name" value="Click!!!" onclick="f1()" />
</div>
<div id="mydiv">
<select id="sel">
<option>لیست شهرهای ایران</option>
</select>
</div>
</body>
</html>
Looks like you are appending the option in the wrong way.
Do it like this:
$.each(data, function(key, value) {
$('#sel').append($("<option></option>").attr("value",item.city_id).text(item.city_name));
});
You could also add a new option like this:
$.each(data, function (key, item) {
$("#sel").get(0).options[$("#sel").get(0).options.length] = new Option(item.city_name, item.city_id);
});

Pass model from 1 partial view to another partial view in the same view

I have 2 partial views being loaded in my main view.
The main view auto refreshes partial view 1 while partial view 2 should only be updated when a user clicks on an Ajax.ActionLink from partial view 1 which should pass the model into partial view 2 and then partial view 2 should be updated.
<div id="lcars">#Html.Partial("LCARS")</div>
<div id="monitorDetail">#Html.Partial("MonitorDetail")</div>
Update Not updating monitorDetail div
Main View
<div id="lcars">#Html.Partial("LCARS")</div>
<br/>
<div id="monitorDetail"></div>
Inside LCARS Partial
<script>
$('#TestButton').on("click", function (event)
{
event.preventDefault();
alert("clicked ajax");
$.ajax({
url: '#Url.Action("MonitorDetail", "NOCCommand", PAL.Intranet.MonitorType.AHSSQLCluster)',
contentType: 'application/json; charset=utf-8',
type: 'POST',
async: false,
dataType: 'html',
data: JSON.stringify(userModel)
})
.success(function (userResult) {
$('#monitorDetail').html(userResult);
})
.error(function (xhr, status) {
});
})
</script>
<div class="lcars-column u-1-3">
<div id="TestButton" class="lcars-button radius">SQL Cluster Online <span class="lcars-button-addition #(mod.SQLClusterOnline ? "online" : "offline")"> #(mod.SQLClusterOnline ? "Online" : "Offline")</span></div>
</div>
UPDATE 2
Here is the code currently. Removing the data throws an error that the value can't be null which is correct.
$.ajax({
type: 'POST',
url: '#Url.Action("MonitorDetail", "NOCCommand")',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
data: {
mType: PAL.Intranet.MonitorType.AHSSQLCluster
},
success: function (data) {
alert("clicked 2"); //doesn't work
$('#monitorDetail').html(data);
},
error: function (xhr, status) {
alert("Error: " + xhr.responseText);
}
})
Update 3
I can now hit the controller but now the div does't show the partial view
Controller
public PartialViewResult AHSSQLClusterDetail()
{
PAL.Intranet.Models.MonitorDetailModel mDetail = new Models.MonitorDetailModel();
mDetail.Item = "test";
mDetail.Val = "test 2";
List<PAL.Intranet.Models.MonitorDetailModel> d = new List<Models.MonitorDetailModel>();
d.Add(mDetail);
return PartialView("MonitorDetail", d);
}
In LCARS Partial View
<script>
$('#TestButton').on("click", function () {
$.ajax({
type: 'GET',
url: '#Url.Action("AHSSQLClusterDetail", "NOCCommand")',
dataType: 'html',
async: false,
cache: false,
success: function (data) {
$("#monitorDetail").html(data);
alert("div loaded");
},
error: function (xhr, status) {
alert("Error: " + xhr.responseText);
}
})
})
</script>
<div id="TestButton" class="lcars-button radius">SQL Cluster Online <span class="lcars-button-addition #(mod.SQLClusterOnline ? "online" : "offline")"> #(mod.SQLClusterOnline ? "Online" : "Offline")</span></div>
Main View
<div id="lcars">#Html.Partial("LCARS")</div>
<br/>
<div id="monitorDetail"></div>
If I understood your problem correctly, I would have done following:
In Main view, I would just load the div1 (partial view 1).
<div id="userSummaryContent" class="tabinsidebox">
#Html.Partial("_OrganizationUserSummary", Model.SummaryViewModel)
</div>
<div id="monitorDetail"></div>
Second div would not load anything initially.
Then I would define a click handler for the link (using its id). In this function I will load the content of second div using AJAX and then just update the second div like:
$(#monitorDetail).html(result);
The handler code would look like this:
$.ajax({
url: '#Url.Action("MonitorDetail", "Test")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
async: false,
dataType: 'html',
data: JSON.stringify(userModel)
})
.success(function (userResult) {
$('#monitorDetail').html(userResult);
})
.error(function (xhr, status) {
});

How to send files to webmethod along with other data? Without using any plug in

Ok so I have a couple of input fields etc I send the data of these field to server side webmethod . WHich is working fine. But I also want to send files to the same webmethod (and not ashx hander) alond with the data of other input fields. Can you please help me out?
This calls webmethod which stored data in database
function SendToServer(name,lineitems) {
$.ajax({
type: "POST",
url: "test.aspx/PostDataWM",
data: JSON.stringify({ name: name,lineitems: lineitems }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
// console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
File Upload MarkUp
<span style="font-family: Arial">Click to add files</span>
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<br />
<br />
<div id="FileUploadContainer">
<!--FileUpload Controls will be added here -->
</div>
<script type="text/javascript">
var counter = 0;
function AddFileUpload() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" class="clsFileUpload" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
}
function RemoveFileUpload(div) {
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>
WebMethod
[WebMethod(enableSession: true)]
public static string PostDataWM(string name,string lineitems)
{
//blah blah
}
No need to stringify the data.
Try it directly. You can get data at your code level
type: "POST",
url: "test.aspx/PostDataWM",
data: { name: name,lineitems: lineitems },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,

ASP.NET a problem with jQuery's ajax function

I have button and that jQuery script (to start the progress bar):
<script src="../_Files/JScripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../_Files/JScripts/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
var intervalID;
$("#<%=this.Button1.ClientID%>").click(
function() {
intervalID = setInterval(updateProgress, 500);
$.ajax({
type: "POST",
url: "CustomerImport.aspx/ExecuteImport",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function()
{
$("#progressbar").progressbar("value", 100);
clearInterval(intervalID);
$("#result").text('ok');
}
});
return false;
}
);
function updateProgress() {
$.ajax({
type: "POST",
url: "CustomerImport.aspx/GetProgress",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#result").text = msg.d;
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", msg.d);
$("#result").text(msg.d);
}
else {
clearInterval(intervalID);
window.location = window.location;
}
}
});
}
the method:
[System.Web.Services.WebMethod]
public void ExecuteImport()
{
_Presenter.ExecuteImport();
}
the problem is, that method is NOT being invoked. Why ?
When I replace the $.ajax for the e.g alert('ok'); the alert shows, so it works
Did you decorate your service class with the [ScriptService] attribute? Also try changing the data parameter to: data: { }. What does FireBug says about this? Is there a request being sent? If yes what does the server respond?
Also you have a mistake in your url (web services have the ASMX extension). You wrote:
CustomerImport.aspx/ExecuteImport
While it should be:
CustomerImport.asmx/ExecuteImport
Here's a complete working example that you may adapt to your needs:
Web service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class CustomerImport : WebService
{
[WebMethod]
public void ExecuteImport()
{
}
}
Calling web page:
<%# Page Language="C#" %>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: '/CustomerImport.asmx/ExecuteImport',
data: { },
success: function () {
alert('ok');
}
});
});
</script>
</head>
<body>
<form runat="server">
</form>
</body>
</html>
Add in the error function to the ajax call... Hopefully you'll get some info back, as to why the call failed.
Are you using firebug? Watch the net tab.
$.ajax({
type: "POST",
url: url,
async: false,
data: jsonEncodedParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}, //success
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == "timeout") {
alert('The request timed out, please resubmit');
} //if
else {
alert(errorThrown);
} //else
} //error
}); //ajax
Since your server-side endpoint is a "page method", it must be declared as static:
[System.Web.Services.WebMethod]
public static void ExecuteImport()
{
_Presenter.ExecuteImport();
}

Categories