I need to upload file in MVC Core via Ajax post request.
My Index.cshtml
<input id="addLogoFile" type="file" class="form-control" accept="image/png" />
<input id="addLogoText" type="text" class="form-control" placeholder="Logo title" />
<button type="button" id="addLogoBtn" class="btn btn-sm btn-success"><span class="glyphicon glyphicon-repeat"></span></button>
$("#addLogoBtn").click(function (e) {
e.preventDefault();
var fileInput = $("#addLogoFile");
var formData = new FormData();
var fileTitle = $("#addLogoText").val();
var file = fileInput[0].files[0];
formData.append(file.name, file);
var request = $.ajax({
url: '#Url.Action("AddLogo", "OrganizationManagement")',
type: "POST",
cache: false,
processData: false,
data: { image: formData, imageName: file.name, title: fileTitle },
datatype: "json"
})
request.done(function (data) {
var logos = $("#Logos");
logos.empty();
$.each(data, function () {
logos.append($("<option />").val(this.Value).text(this.Text));
})
})
request.fail(function (e) {
$("#addLogoText").val(e.responseText);
})
})
My ExampleController.cs:
[HttpPost]
public async Task<JsonResult> AddLogo(IFormFile image, string imageName, string title)
{
//code doesn't matter, null in image, imageName and title
}
The problem, is that image, imageName, title are always null. How should I fix it?
EDIT
If I add contentType: false i have this error in my Network Debugger: The server encountered an unexpected condition that prevented it from fulfilling the request
Related
The program does the following steps:
The user clicks on Change Address
The button disappears, another button appears - Save.
Next, the program should read the data from the input and send it via ajax to the controller method.
But nothing works. When I put everything in one <script> tag, the first button also stops working. Help
The problem is that even the buttonSetAddress button does not perform the function. It starts working only after I remove everything else from <script>
<div class="form-group">
<label>Адресс</label>
<input class="form-control" id="AddressInput" type="text" placeholder="#ViewBag.User.Address" readonly /><br />
<button type="button" class="btn btn-primary" id="buttonSetAddress">Изменить</button>
<button type="button" class="btn btn-success" id="buttonSaveAddress" onclick="SaveAddress()" hidden>Сохранить</button>
</div>
js and ajax
<script type="text/javascript">
document.getElementById('buttonSetAddress').onclick = function AddressInputSet() {
document.getElementById('AddressInput').removeAttribute('readonly');
document.getElementById('buttonSetAddress').hidden = 'true';
document.getElementById('buttonSaveAddress').removeAttribute('hidden');
alert('sdfgdfg');
};
document.getElementById('buttonSaveAddress').onclick = function SaveAddress() {
var data = JSON.stringify( {
userId: #ViewBag.User.Id,
address: document.getElementById('AddressInput').value
});
$.ajax({
type: 'POST',
url: '/Account/ResetAddress',
data: data,
dataType: JSON,
success: function () {
document.getElementById('buttonSaveAddress').hidden = 'true';
},
error: function () {
alert('Error');
}
});
};
</script>
Controller
[HttpPost]
public async void ResetAddress(string userId, string address)
{
var user = await _userManager.FindByIdAsync(userId);
user.Address = address;
await _userManager.UpdateAsync(user);
}
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Since your action return void, you could not set the dataType as JSON.
Try to use below code which works well(Make sure the url is correct)
<div>
<label>Адресс</label>
<input class="form-control" id="AddressInput" type="text" placeholder="#ViewBag.User.Address" readonly /><br />
<button type="button" onclick ="AddressInputSet()"class="btn btn-primary" id="buttonSetAddress">Изменить</button>
<button type="button" onclick="SaveAddress()" class="btn btn-success" id="buttonSaveAddress" hidden>Сохранить</button>
</div>
#section Scripts{
<script type="text/javascript">
function AddressInputSet() {
document.getElementById('AddressInput').removeAttribute('readonly');
document.getElementById('buttonSetAddress').hidden = 'true';
document.getElementById('buttonSaveAddress').removeAttribute('hidden');
alert('sdfgdfg');
};
function SaveAddress() {
var data ={
userId: #ViewBag.User.Id,
address: document.getElementById('AddressInput').value
};
$.ajax({
type: 'POST',
url: '/Account/ResetAddress',
data: data,
//contentType: "application/x-www-form-urlencoded; charset=utf-8",
//dataType: JSON,
success: function () {
document.getElementById('buttonSaveAddress').hidden = 'true';
},
error: function () {
alert('Error');
}
});
};
</script>
}
Action:
[HttpPost]
public async void ResetAddress(string userId, string address)
try add quote to this value
var data = {
userId: '#ViewBag.User.Id', // here
address: document.getElementById('AddressInput').value
};
var data =JSON.stringify( {
userId: '#ViewBag.User.Id', // here
address: document.getElementById('AddressInput').value
});
You have to use JSON.stringify to turn you object to json.
and also yo must set content type in ajax
I want to pass selected value of dropdownlist from view to controller in html.BeginForm in MVC 4.
I can pass value of query string, but I have no idea about how to pass selected value of dropdownlist.
All suggestions are most welcome.
Here is my code attached
<form>
<fieldset class="form-group" id="ddl2">
<label for="exampleSelect1">Section Type:</label>
#(Html.Kendo().DropDownList()
.Name("ddlsection")
.DataTextField("Name")
.DataValueField("Id")
.OptionLabel("--Select--")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetSectionType", "LookUp");
});
})
.Events(e => e.Change("onChange_ddlsection"))
.HtmlAttributes(new { #class = "form-control" })
)
</fieldset>
</form>
<div class="WordClass">
#using (Html.BeginForm("GetConditionListingInWord", "Inspection", new { sectionId = 'What should be here?' }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="Submit1" type="submit" value="" class="WordClassA tooltipSource" title='Print List in MS-Word format' data-placement='bottom' data-toggle='tooltip' />
}
</div>
I want 'ddlsection' dropdown's selected value in 'What should be here?' section.
You can pass Kendo Dropdownlist's selected value to the Controller using Ajax call and then redirect to another Action if you want as shown below:
<script type="text/javascript">
$(function () {
//Returns Dropdownlist's selected values to the Controller
$("#btnSubmit").click(function (e) {
e.preventDefault();
var data = {
ProjectID: $('#ProjectID').val(), //parameter I
IssueID: $('#IssueID').val() //parameter II
}
$.ajax({
type: "POST",
url: "/Controller/Action",
cache: false,
data: JSON.stringify(data),
dataType: this.dataType,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Variable data contains the data you get from the action method
window.location = "/Controller/OtherAction/" + data
},
error: function (data) {
$("#error_message").html(data);
}
});
});
});
</script>
For that you have to make AJAX call to your controler method
var userModel = {
RoleId: $("#drpRoleId").data("kendoDropDownList").value(),
}
$.ajax({
url: '#Url.Action("AddEditUser","User")',
type: 'POST',
data: JSON.stringify(userModel),
async: true,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});
file.aspx
<form action="data/exec.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="image" required="required" id="image"/>
<button type="submit">submit</button>
</form>
exec.aspx
HttpPostedFile file = Request.Files["image"];
if (file != null && file.ContentLength > 0 )
{
try
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine("../images/" + fname)));
Response.Write("done " + fname);
}
catch (Exception ex)
{
Response.Write(ex);
}
}
When I submit the form, nothing happens and file is null. I also tried asp:file upload but had the same problem.
Similar code worked on php example on exec.php page $_FILES["image"]["name"] it posts image and saves, but it doesn't work in ASP.NET cross page post.
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<input type="file" name="doc" id="doc" />
<button type="submit">Submit</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$("form#form1").submit(function () {
var formData = new FormData($(this)[0]);
$.ajax({
url: 'recive.aspx',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
i am using jquery and ajax to post data from another form
recive.aspx
HttpPostedFile file = Request.Files["doc"];
if(file!=null)
{
string fname = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath(Path.Combine(fname)));
Response.Write("done " + fname);
}
else
{
Response.Write("file empty");
}
I'm trying to get and pass my ViewModel to my Json method doing the stuff like this :
In my view :
<input type="button" id="suggestionBtn" title="Suggestion" onclick ="location.href='#Url.Action("GetNextAppointment", "Home", new { svm = Model })'" />
In my Controller :
public JsonResult GetNextAppointment(SuggestionViewModel svm)
{
return Json(svm, JsonRequestBehavior.AllowGet);
//this is just for testing
}
While debugging, I found out that my svm is null. I tried to replace it by a string parameter and hard coding the value in my view and this works. So, I don't know very much where is the problem.
Any idea guys?
EDIT : Code edited to use jQuery AJAX
My view's now like this :
#model AstellasSchedulerV2.Models.SuggestionViewModel
<div class="rightPanel">
#using (Html.BeginForm("NewAppointment", "Home", FormMethod.Post, new { #id = "form_ValidateAppointment" }))
{
#Html.Hidden("stringParam","")
<fieldset>
<div>
Patch Anti-douleur Corps #Html.CheckBoxFor(s => s.PADC, new { #class = "checkbox", #id = "chbxPADC" })
</div>
<br />
<div>
Patch Anti-douleur Pied #Html.CheckBoxFor(s => s.PADP, new { #class = "checkbox", #id = "chbxPADP" })
</div>
<br />
Click me
</fieldset>
}
</div>
<script type ="text/javascript">
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.PADC = $("#chbxPADC").val();
o.PADP = $("#chbxPADP").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) { alert(data.PADC); },
failure: function (errMsg) { alert(errMsg); }
});
});
</script>
Here goes the solution, Lets say you have your viewmodel this way -
public class SuggestionViewModel
{
public bool PADC { get; set; }
public bool PADP { get; set; }
}
Then you have a View in the following way. Here I used JQuery to make a POST request to GetJson Controller Action. I constructed a JavaScript Object and then serialized it to Json. Then finally passed the Json string to Controller Action.
<fieldset>
<div>
Patch Anti-douleur Corps #Html.CheckBoxFor(s => s.PADC, new { #class = "checkbox", #id = "chbxPADC" })
</div>
<br />
<div>
Patch Anti-douleur Pied #Html.CheckBoxFor(s => s.PADP, new { #class = "checkbox", #id = "chbxPADP" })
</div>
<br />
</fieldset>
This is the JQuery part -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var chk = $('#chbxPADC').is(':checked');
var chk1 = $('#chbxPADP').is(':checked');
var o = new Object();
o.PADP = chk1;
o.PADC = chk;
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) { alert(data.PADP); },
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
Click me
And when you click the button, it will hit following controller -
public JsonResult GetJson(SuggestionViewModel svm)
{
return Json(svm, JsonRequestBehavior.AllowGet);
}
And when you inspect the parameter using breakpoint, you will have parameters passed -
And as the response, you will have following output -
You can't post complex objects as parameter.
If you want to get json result, you should call an ajax request.
You should post your model in an ajax request. (you can use jquery .ajax metod), because you cant get values from controller action metod if you use location.href
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,