How to send Id and file to same controller? - javascript

"i want to send id and file data to same action uploadFile(int id, httpPostFileBase upFile) ?"
i tried to send the patient id via ajax during submit, and file using name attribute in input tag.
#using (Html.BeginForm("uploadFile", "patientsProfile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="upFile" />
<br />
<input type="submit" name="submit" value="Upload!" />
}
var id = url.substring(url.lastIndexOf('/') + 1);
$("form").submit(function (e) {
$.ajax({
type: "POST",
url: "#Url.Action("uploadFile","patientsProfile")",
data: {
Id: id
},
success: function (res) {
alert("id :" + id);
}
})
})
[HttpPost]
public ActionResult uploadFile( HttpPostedFileBase upFile , int Id)
{
Tests tests = new Tests();
tests.patients_Id = Id;
string fileName = upFile.FileName;
string UniquefileName = Guid.NewGuid() + Path.GetFileName(upFile.FileName);
string filePath = Server.MapPath("~/Uploaded/");
string actualPath = Path.Combine(filePath + UniquefileName);
upFile.SaveAs(actualPath);
tests.Name = fileName;
tests.urlName = actualPath;
db.Tests.Add(tests);
db.SaveChanges();
return RedirectToAction("index");
}
httpPostFileBase upFile be null but id take it's value correctly

First of all I think that the below code is going to cause issues
var id = url.substring(url.lastIndexOf('/') + 1);
Reasons
If it is used to get the id when the ids are only one character then it works well, but when the number of character increases it is going to get wrong values. example for a url www.yourdomain.com/controller/action/1 it will work fine, but www.yourdomain.com/controller/action/12 will return the same result as the first. So you might want to do some math there like (stringLength - lastIndexOf / )
I will suggest you use ViewBag to get that Id since it was passed from the GET method and then pass that to the form as a parameter like below
#using (Html.BeginForm("uploadFile", "Home", new{Id = ViewBag.Id}, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="upFile" id="upFile" />
<br />
<input type="submit" name="submit" value="Upload!" />
}
remember to include the view bag in the get request as
public ActionResult ActionName(int Id)
{
ViewBag.Id = Id;
return View();
}
IF you insist on using javascript then try including the file as a data like in this answer

#using (Html.BeginForm("uploadFile", "Home", new{Id = ViewBag.Id},
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="upFile" id="upFile" />
<input type="hidden" name="hdfid" id="hdfid" value ="" />
<br />
<input type="submit" name="submit" value="Upload!" />
}
var id = url.substring(url.lastIndexOf('/') + 1);
$("#hdfid").val(id);
$("form").submit(function (e) {
$.ajax({
type: "POST",
url: "#Url.Action("uploadFile","patientsProfile")",
success: function (res) {
alert("id :" + id);
}
})
})
public ActionResult uploadFile( formcollection form, HttpPostedFileBase
upFile )
{
Tests tests = new Tests();
string id = form["id"];//or provide index
tests.patients_Id = Id;
string fileName = upFile.FileName;
string UniquefileName = Guid.NewGuid() +
Path.GetFileName(upFile.FileName);
string filePath = Server.MapPath("~/Uploaded/");
string actualPath = Path.Combine(filePath + UniquefileName);
upFile.SaveAs(actualPath);
tests.Name = fileName;
tests.urlName = actualPath;
db.Tests.Add(tests);
db.SaveChanges();
return RedirectToAction("index");
}

you have to pass the upFile to to the data which you are sending.
data: {
Id: id,
upFile: //the file which you are sending
},

Related

add more picture instead of replacing picture in asp.net core mvc

i create a form where i upload picture into database in asp.net core mvc using ado.net.i face an issue that when i select picture it selects the picture but if i do one more time instead of add more picture it replace that picture which i select first help me to that thing in which i add further more picture. i create a list in which i upload the picture.Here is my code.
My Controller:
public IActionResult aprent([Bind] RentModel ar )
{
try
{
if (ModelState.IsValid)
{
if(ar.imge1 != null && ar.imge1.Count>0)
{
string folder = "image/";
foreach (IFormFile imge in ar.imge1)
{
folder += Guid.NewGuid().ToString() + "_" + imge.FileName;
ar.pic1 = "/" + folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
imge.CopyTo(new FileStream(serverFolder, FileMode.Create));
}
}
string res = DB.Saverecord(ar);
string pics = DB.imagedb(ar);
TempData["msg"] = res;
}
}
catch (Exception ex)
{
TempData["msg"] = ex.Message;
}
return View();
}
My Model:
public string? pic1 { get; set; }
public IFormFileCollection imge1 { get; set; }
My View:
<div class="row">
<input type="file" name="imge1" id="file" asp-for="imge1" class="hidden" multiple>
<button type="button" class="btn btn-primary" id="filebutton"><span id="filetext">Select File</span></button>
<div id="preview"></div>
</div>
<div id="image_preview"></div>
<script>
$(document).ready(function () {
$('#filebutton').click(function () {
$('#file').click();
});
$('#file').change(function () {
var name = $(this).val().split('\\').pop();
var file = $(this)[0].files;
if (name != '') {
if (file.length >= 2) {
$('#filetext').html(file.length + ' files ready to upload');
}
else {
$('#filetext').html(name);
}
}
});
$('#file').on("change", previewImages);
});
function previewImages() {
var $preview = $('#preview').empty();
if (this.files) $.each(this.files, readAndPreview);
function readAndPreview(i, file) {
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
$(reader).on("load", function () {
$preview.append($("<img>", { src: this.result, height: 80, }));
});
reader.readAsDataURL(file);
}
}
</script>
Do you want to choose more pictures at one time ?
Something like below? Hold down the Shift key when you choose pictures.
Update
if i select picture and after that i hit the choose button one more
time it select further more picture but not replace the previous
selected picture
i have also other data also i have same model in which my data exist
when i post form
You can try to use jQuery FilePond.
Below is a work demo, you can refer to it.
TestController:
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(Testmodel testmodel,IFormFile[] photos)
{
return View();
}
}
Testmodel:
public class Testmodel
{
public string Name { get; set; }
public IList<IFormFile> photos { get; set; }
}
Index view:
#model Testmodel
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
<form id="uploadform" enctype="multipart/form-data">
<input type="text" asp-for="Name" />
<input type="file" class="filepond"asp-for="photos">
<button type="submit" class="uploadbtn">Upload Document</button>
</form>
<script>
$(document).ready(function(e){
pond = FilePond.create(
document.querySelector('.filepond'), {
allowMultiple: true,
instantUpload: false,
allowProcess: false
});
$("#uploadform").submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
// append FilePond files into the form data
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
// append the blob file
formdata.append('photos', pondFiles[i].file);
}
$.ajax({
url: "/test/Index",
data: formdata,
processData: false,
contentType: false,
method:"post"
});
})
});
</script>
result:

Sending url with parameter to action function via javascript

I am trying to open new window using window.open(actionUrl)
the actionUrl is compose form the action address and url as parameter.
so eventually the actionUrl is :
"/Default/Details?url=http://www.someaddress.com?a1=1&a2=2&a3=3"
However in the action the url i get is :
"http://www.someaddress.com?a1=1"
I do not get "&a2=2&a3=3" parameters
Here is the relevant view code:
<div>
<input type="button" value="test" id="btnTest" />
</div>
<script>
var vurl = '#Url.Action("Details", "Default")';
$(function () {
$("#btnTest").click(function () {
var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
vurl = vurl + url;
window.open(vurl);
});
})
</script>
and this is the controller and action
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
// GET: Default/Details/5
public ActionResult Details(string url)
{
return View();
}
}
You need to use the encodeURIComponent function on the url parameter's value:
var actionUrl = '/Default/Details?url=' + encodeURIComponent('http://www.someaddress.com?a1=1&a2=2&a3=3');
The &a2=2&a3=3 part was actually part of the /Default/Details URL, not the http://www.someaddress.com one. Now that the inner URL is URI encoded, it should work.
Make sure to decode the value when using the url parameter though, using decodeURIComponent:
var urlMatch = location.search.match(/url=(.*)&?/);
if (urlMatch) {
var decodedUrl = decodeURIComponent(urlMatch[1]);
// do something with the decoded URL...
}
EDIT
For the first part (URI encoding) and based on your code, you should use it this way:
<div>
<input type="button" value="test" id="btnTest" />
</div>
<script>
var vurl = '#Url.Action("Details", "Default")';
$(function () {
$("#btnTest").click(function () {
var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
vurl = vurl + encodeURIComponent(url);
window.open(vurl);
});
})
</script>
As for the ASP.NET part and the use of the string url parameter, I'd suggest checking the following post: using decodeURIComponent within asp.net as I'm not familiar with this environment.

Getting Null response instead of json in jquery post from aspx.cs page

I am working on simple application where i am hitting the Request.aspx page from default2.aspx using jquery ajax post method as you can see below:
js page:
$(document).ready(function () {
$("#login").click(function () {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "Request.aspx?Login=True",
data: "{'username': '" + email + "','password': '" + password + "'}",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var url = "http://google.com";
//$(location).attr('href', url);
}
});
});
});
Default.aspx:
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/LoginCode.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="container">
<div class="main" id="loginform">
<label>
Email :</label>
<input type="text" name="demail" id="email" />
<label>
Password :</label>
<input type="password" name="password" id="password" />
<input type="button" name="login" id="login" value="Login" />
</div>
</div>
</div>
</form>
</body>
Request.cs Page:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Login"] != null)
{
test();
};
}
private string test()
{
var response = new ResponseResult();
var javaScriptSerializer = new JavaScriptSerializer();
response.Status = -1;
response.ErrorMessage = "";
response.Action = "UserProjects";
response.Data = "The Username or password you entered is not valid";
return javaScriptSerializer.Serialize(response);
}
public class ResponseResult
{
public string Action { get; set; }
public int Status { get; set; }
public string ErrorMessage { get; set; }
public object Data { get; set; }
}
Problem:
In response NUll is coming but i am expected json. Please let me know where i am going wrong.
If you need more info i will try my best to provide.
Thanks in advance.
It is a good idea to use Restful Webservices or Web Method to call from AJAX.
But still you can do the following.
Use Response.Write() instead of returning string.
Use this code.
private void test()
{
var response = new ResponseResult();
var javaScriptSerializer = new JavaScriptSerializer();
response.Status = -1;
response.ErrorMessage = "";
response.Action = "UserProjects";
response.Data = "The Username or password you entered is not valid";
string result = javaScriptSerializer.Serialize(response);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(result); //write json string to output
}

Request method 'POST' not supported Spring Boot

Basically, I have a HTML search form which allows me to search within the database. A JavaScript function is called when the form is submitted but I'm not redirected to the required page.
"Request method 'POST' not supported" is the error message received.
My code:
<form th:object="${devices}" method="POST" onsubmit="return fireAction()">
<input type="text" id="search" name="search" />
<input type="submit" value="Search"/>
</form>
function fireAction() {
var searchInput = document.getElementById('search').value;
var searchFilter = document.getElementById('deviceAttributes').value;
var checkbox = document.getElementById('lastEntry').checked;
alert(searchInput + " " + searchFilter + " " + checkbox);
if (searchInput == "" || searchInput == null) {
alert("Search field cannot be null.");
return false;
} else if (checkbox) {
window.location.href = '/current/' + searchInput
+ '/filter/' + searchFilter;
} else {
window.location.href = '/showForm/' + searchInput
+ '/filter/' + searchFilter;
}
}
#RequestMapping(value = "/showForm/{keyword}/filter/{searchFilter}", method = RequestMethod.POST)
public String showForm(#PathVariable("keyword") String keyword,
#PathVariable("searchFilter") String searchFilter, Model model) {
Devices devices = new Devices();
devices.setSearch(keyword);
devices.setSearchFilter(searchFilter);
model.addAttribute(
"addDevices",
device.findByDevicesName(devices.getSearch(),
devices.getSearchFilter()));
return "showForm";
}
#RequestMapping(value = "/current/{keyword}/filter/{searchFilter}", method = RequestMethod.POST)
public String currentDevices(#PathVariable("keyword") String keyword,
#PathVariable("searchFilter") String searchFilter, ModelMap model) {
model.addAttribute("devices", new Devices());
Devices devices = new Devices();
devices.setSearch(keyword);
devices.setSearchFilter(searchFilter);
List<Devices> newList = device.allDevices();
ListIterator<Devices> iterator = newList.listIterator();
List<Devices> resultList = new ArrayList<Devices>();
while (iterator.hasNext()) {
Devices device = iterator.next();
if (searchLastEntry(device, keyword, searchFilter)) {
resultList.add(device);
}
}
model.addAttribute("iterator2", resultList);
return "current";
}
You don't have a return false in your javascript after executing the window.location.href - So i suspect that after the javascript executes the asynchronous GET request to window.location.href, then the function ends and control is passed back to the form, which just does the normal POST action, but you haven't defined an action URL (which explains the GET then POST requests you say you have seen in the network tab).
Aside, as mentioned in the comments, you probably shouldn't be using POST for a search form - Have a look at http://www.w3schools.com/tags/ref_httpmethods.asp

MVC upload and save form image with Ajax

I have a form with 3 inputs (text, image, submit button).
#using (Html.BeginForm("Save", "User", FormMethod.Post, new {Id="Form1", enctype = "multipart/form-data"}))
{
<input id="FileUploadInput" name="Image" type="file"/>
<input id="FirstName" Name="FirstName">
<input type="submit" id="inputSubmit" value="Save" />
}
Now i want to submit this form from javascript with AJAX
$("#inputSubmit").click(function (e) {
e.preventDefault();
var form = $("#Form1");
form.validate();
if (form.valid()) {
$.ajax({
url: "/User/Save",
data: form.serialize(),
type: "POST",
success: function (data) {
if (data === "") {
location.reload();
}
else {
$(".content").html(data);
$.validator.unobtrusive.parse($(".content"));
}
}
});
}
return false;
});
In my controller file i have.
public ActionResult Save(UserProfileSettings settings)
{
var image = setings.Image
var name = settings.Firstname
}
My model
public class UserProfileSettings
{
public string FirstName { get; set; }
public HttpPostedFileBase Image { get; set; }
}
The problem is that in my controller method i am getting settins.FirstName, but settings.Image is always null. I think, that with this method it is not possible to serialize image file.
try use jquery plugin muliple upload:
http://blueimp.github.io/jQuery-File-Upload/
As Darin Dimitrov suggested before, it's better to use jquery forms plugin. I have already posted this in my another answer here.
Quick Example
View
#using (Ajax.BeginForm("YourAction", "YourController", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
#Html.AntiForgeryToken()
<input type="file" name="files"><br>
<input type="submit" value="Upload File to Server">
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public void YourAction(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
}
}
}
}

Categories