In MVC 4 my textarea is not resetting from default value - javascript

I've created a MVC project with Browse button and upload button. When the user clicks on Browse and select a file and click upload, the file contents has to be displayed in a Textarea. By default when I load the page, I'm displaying default text in textarea. Once the user uploads a file, I'm trying to display the contents in that textarea.
Problem is while I'm trying to reset the content, the textarea is not getting reset. Any help is really appreciated.
View:-
#model DigitalUnderwritingFacade.Models.DigitalUnderwritingModel
<h2>DigitalUnderwriting</h2>
<div>
#using (Html.BeginForm())
{
<table style="vertical-align:middle">
<tr>
<td>Upload a json file : <input type="file" id="btnbrowse" name="browse" value="Browse"></td>
</tr>
<tr>
<td><input type="button" id="btnfileUpload" name="btnfileUpload" value="Upload" /></td>
<td><div id="validateSelectedFile" class="warrningMessage">Please browse a valid json file</div></td>
</tr>
<tr>
<td>#Html.TextAreaFor(model => model.JsonText, new { #class = "form-control", cols = "120", rows = "45", #id = "textarea" })</td>
</tr>
<tr>
<td><input type="submit" id="Savebtn" value="Save"></td>
</tr>
</table>
}
</div>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$("#btnfileUpload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("btnbrowse").files.length;
var browsedFile = document.getElementById("btnbrowse").files[0];
var fileextension = browsedFile.name.split('.').pop();
if (totalFiles == 0)
$("#validateSelectedFile").show()
if ((totalFiles != 0)) {
if (fileextension == 'json') {
formData.append("FileUpload", browsedFile);
$.ajax({
type: "POST",
url: '/DigitalUnderwriting/Upload',
data: formData,
contentType: false,
processData: false,
success: function (result) { }
});
}
else {
alert("Please select a valid json file.");
}
}
});
</script>
Controller:-
DigitalUnderwritingModel model = new DigitalUnderwritingModel();
private string InputJsonPath = System.Configuration.ConfigurationManager.AppSettings["DefaultJson"].ToString();
private string ResponseJsonPath = System.Configuration.ConfigurationManager.AppSettings["JsonResponsesPath"].ToString();
//
// GET: /DigitalUnderwriting/
public ActionResult Index()
{
StreamReader reader = new StreamReader(InputJsonPath);
if (TempData["ResponseJson"] == null)
{
model.JsonText = reader.ReadToEnd();
}
else
{
model.JsonText = TempData["ResponseJson"].ToString();
TempData["ResponseJson"] = null;
}
return View(model);
}
[HttpPost]
public ActionResult Upload()
{
ModelState.Remove("JsonText");
var streamfile = new StreamReader(Request.Files[0].InputStream);
var streamline = string.Empty;
while((streamline = streamfile.ReadLine()) != null)
{
model.JsonText += streamline;
}
TempData["ResponseJson"] = model.JsonText;
return RedirectToAction("Index");
}
Model:-
[DataType(DataType.MultilineText)]
public string JsonText { get; set; }

Try this, my friend. I think you dont need set id for Textarea.
$("#btnfileUpload").click(function () {
var formData = new FormData();
var totalFiles = document.getElementById("btnbrowse").files.length;
var browsedFile = document.getElementById("btnbrowse").files[0];
var fileextension = browsedFile.name.split('.').pop();
if (totalFiles == 0)
$("#validateSelectedFile").show()
else{
$('#JsonText').html(browsedFile.name); //set name file
if (fileextension == 'json') {
formData.append("FileUpload", browsedFile);
$.ajax({
type: "POST",
url: '/DigitalUnderwriting/Upload',
data: formData,
contentType: false,
processData: false,
success: function (result) { }
});
}
else {
alert("Please select a valid json file.");
}
}
});
[HttpPost]
public ActionResult Upload()
{
TempData["ResponseJson"] = model.JsonText;
ModelState.Remove("JsonText");
var streamfile = new StreamReader(Request.Files[0].InputStream);
var streamline = string.Empty;
while((streamline = streamfile.ReadLine()) != null)
{
model.JsonText += streamline;
}
return RedirectToAction("Index");
}

Related

Ajax doesn't work by retrieving big file from database

By retrieving file more than 0.5MB from SQL database ajax falls into error every time, what am I doing wrong here?
$(document).ready(function () {
loadFileData();
});
function loadFileData() {
$.ajax({
type: "GET",
url: "/File/FileIndex",
dataType: "JSON",
success: function (data) {
$.each(data, function (i, val) {
var trow = $('<tr/>').data("id", val.id);
var trowa = $('<tr/>');
var trowb = $('<tr/>').data("id", val.id);
trow.append('<td colspan="2">' + escape(val.Name) +'</td>');
trowa.append('<td><input type="file" id="FileUpload" /></form></td>');
trowb.append('<td><input type="button" class="btnUpload" value="Upload File" /><input type="button" id="btnClear" value="Clear" /></td>');
tab.append(trow);
tab.append(trowa);
tab.append(trowb);
});
$("#showFiles").html(tab);
},
error: function (error) {
alert("Failed! Please try again." + error);
}
});
var tab = $('<table style="width:100px" border=1 class=MyTable></table>');
}
my controller:
//GET: File
public JsonResult FileIndex()
{
List<tblFile> fileList = new List<tblFile>();
using (FileDBEntities db = new FileDBEntities())
{
fileList = db.tblFiles.ToList();
}
return new JsonResult { Data = fileList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
with small files it works perfectley, but why it falls down by retriving file more than 0,5MB?
message, what I'm reciving:
function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?
(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}
I think you should:
Your Controller: you should return with binary || file Stream
//GET: File
public JsonResult FileIndex()
{
List<byte> fileList = new List<byte>();
using (FileDBEntities db = new FileDBEntities())
{
fileList = db.tblFiles.ToList();
foreach(var itemFile in fileList) {
fileList.add(File.ReadAllBytes(itemFile));
}
}
return new JsonResult { Data = fileList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

How to keep list of image files in a var [] and send them to controller at once

I need to send array of image files to a controller. Below I have sent one file to the controller, but I need to send a list of image files.
My Controller:
public async Task<IActionResult> AddImage(string emailid , List<IFormFile> imagefile)
{
ImageUpload img=new ImageUpload();
var emailId = feedBackContext.UserMasters.FirstOrDefault(m=>m.Email==emailid);
foreach (var item in imagefile)
{
if (item.Length > 0)
{
using (var stream = new MemoryStream())
{
await item.CopyToAsync(stream);
img.imagefile = stream.ToArray();
}
}
}
img.EmailID = emailId.UserMasterID;
var existimage = feedBackContext.ImageUpload.FirstOrDefault(m => m.EmailID == emailId.UserMasterID);
if (existimage == null)
{
feedBackContext.ImageUpload.Add(img);
feedBackContext.SaveChanges();
return RedirectToAction("Index");
}
else
{
feedBackContext.ImageUpload.Remove(existimage);
feedBackContext.SaveChanges();
feedBackContext.ImageUpload.Add(img);
feedBackContext.SaveChanges();
return RedirectToAction("Index");
}
}
My JavaScript file:
(I need to send array of image files to the controller like passing array)
function sendArr(form)
var []=imgarr;
{
$.ajax(
{
type: "POST",
traditional: true,
url: form.action,
data: { dataList: arr, imageList: imgarr },
dataType: "json",
success: function (asd) {
document.getElementById("QuestionDescription").value = "";
document.getElementById("AnswerDescription").value = "";
count = 0;
$('#demo').remove();
document.getElementById("QuestionDescription").focus();
window.location.href = '';
}
});
}
}
My Form::
<script>
function addAnswer() {
imgarr[count] = document.getElementById('imagefile').value;
}
</script>
<form asp-action="AddImage">
<input type="file" id="imagefile" name="imagefile" />
</form>
Help me if you know something regarding this.
Consider your form looks similar to this:
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
Controller:
You need to use IEnumerable<HttpPostedFileBase>
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
foreach (var file in files) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
The files variable refers to the name attribute in the form fields.
You can also stuff the variable inside a model if you like.
Example taken from here

My Request.Files in action side is always null when uploading file by ajax in MVC

I need to upload an image by ajax mode in MVC .I used this method everything is ok in Js code it gets the formdata and the ajax request is sent to the controller correctly but in my controler i get Request.File["myfile"] always null ... i seached everywhere for the solution but didn't find please help me thats so emergency ... Thank's all
here is my js codes :
function UploadImage() {
var data = new FormData();
var files = $("#myfile").get(0).files;
if (files.length > 0) {
data.append("MyImages", files[0]);
}
$.ajax({
url: "#Url.Action("SaveFile","Home")",
type: "POST",
processData: false,
contentType: false,
enctype: 'multipart/form-data',
data: {},
success: function (response) {
//code after success
console.log(response);
alert(response);
},
error: function (er) {
alert(er);
}
});
}
Html:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>upload</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div class="row">
<div class="container">
<div>
file:<input type="file" id="myfile" style="display: block"/>
<br />
<input type="button" value="save" id="btnUpload" onclick="UploadImage()"/>
</div>
</div>
</div>
</body>
</html>
and My Action:
[HttpPost]
public JsonResult SaveFile()
{
var uniqueName = "";
if (Request.Files["myfile"] != null)
{
var file = Request.Files["myfile"];
if (file.FileName != "")
{
var ext = System.IO.Path.GetExtension(file.FileName);
uniqueName = System.Guid.NewGuid().ToString() + ext;
var rootPath = Server.MapPath("~/Upload/");
var fileSavePath = System.IO.Path.Combine(rootPath, uniqueName);
file.SaveAs(fileSavePath);
}
}
return Json(new
{
success=false,
name=uniqueName
},JsonRequestBehavior.AllowGet);
}
Following this example that is very similar to your code
change this
data: {}
by this
data: data
Sample code VIEW
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
fileData.append('username', ‘Manas’);
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Sample Code CONTROLLER
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

Unable to retrieve data from html

As for my below code i am not able to get sectionID from tr, i need to get dynamic id of sectionID on each delete button click but it is always giving me null
Here is the Jquery Script :
<script>
$(function () {
$('.btnDelete').click(function () {
var sectionID = $(this).closest('tr').find('.sectionID');
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'CheckSectionIDagainststudentID',
data: JSON.stringify({ sectionID: sectionID.html() }),
success: function (data) {
if (data == true) {
$.alert("Cannot delete | Students exsisting in this
Section!");
}
else if (data == false) {
var secCode = JSON.parse(this.data);
var code = sectionid['sectionid'];
window.location.href = "SectionDelete?Page=data&sectionid="
+ code;
}
},
failure: function (response) {
$('#result').html(response);
}
});
});
});
</script>
and here is Razor Page
#foreach (var item in Model)
{
<tr class="sectionID">
<td >
#Html.DisplayFor(modelItem => item.sectionID)
</td>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td class="secCode">
<button style="width:49.5%" ID="Button2" type="button" onclick="location.href='#Url.Action("SectionEdit", "Section",new { id = item.sectionID, name = item.name })'">Edit</button>
<button style="width:49.5%" ID="deletebtn" runat="server" type="button" onclick="location.href='#Url.Action("SectionDelete", "Section",new { id = item.sectionID, name = item.name })'">Delete</button>
<button class="btnDelete">Delete</button>
</td>
</tr>
}
This is Controller Which i need to pass data to
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string sectionID)
{
return Json(sectionID);
}
As per your question you are not able to get value from var sectionID = $(this).closest('tr').find('.sectionID');
therefore here is a way you can achieve your result
//Your Dynamic Button should look like this
//in value Bind your sectionID # MVC
<button class="btnDelete" value="5" onclick="AjaxDelete(this)">Delete</button>
//For Function
function AjaxDelete(values) {
//Write this in Ajax
//Fetch Value from attribute value
var sectionID = $(values).attr("value"); // you will get 5 as value
//Your Ajax Call with SectionId as Parameter
}
Edit :
as you have got value
U can split the value by below code
where string is your var of sectionID
if ((~string.indexOf('\n '))) {
string= string.split('\n ')[1].split('\n')[0];
}
Use string array :
[HttpPost]
public ActionResult CheckSectionIDagainststudentID(string[] sectionID)
{
return Json(sectionID);
}

how send table content to controller

I have a problem to send table global from view to controller the table in controller is full but in controller affect a null for the composant of table
and this is the controller method :
public Boolean ajoutermodule(string nom, modules[] global, int cv)
{
return true;
}
And this the view and method ajax how i append my table global and how i sent this table global from view to controller :
function Addmodule() {
var nom = $("#nomprojet_I").val();
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"global": global,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
var global = [];
function OnGetSelectedFieldValues(s, e) {
var SelectedUsers = $("#teamlist_I").val() + " " + $("#teamid_I").val();
listbox.AddItem(SelectedUsers);
var nom = $("#teamlist_I").val();
var id = $("#teamid_I").val();
global.push({ "id": id, "nom": nom });
debugger;
}
and when i added the length it send him correctly to controller.
but method ion your controller like this:
public Boolean ajoutermodule(string nom, stirng s, int cv)
{
return true;
}
and add this to your method ajax
var s = JSON.stringify(global);
function Addmodule() {
var nom = $("#nomprojet_I").val();
var s = JSON.stringify(global);
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"s": s,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
it will work inchallah
Please try this code for ASP.NET MVC –
View.cshtml
<table id="StepsTable">
<tr>
<td>Step 1</td>
<td>#Html.TextBox("step1")</td>
</tr>
<tr>
<td>Step 2</td>
<td>#Html.TextBox("step2")</td>
</tr>
<tr>
<td>Step 3</td>
<td>#Html.TextBox("step3")</td>
</tr>
</table>
<input id="SendToControllerButton" type="button" value="Send to the server"/>
<script>
$(document).ready(function () {
$("#SendToControllerButton").click(function () {
var data = {};
//Collects the data from textboxes and adds it to the dictionary
$("#StepsTable tr").each(function (index, item) {
var tds = $(this).find("td");
var textBoxTitle = $(tds).eq(0).text();
var textboxValue = $(tds).eq(1).find("input").val();
data["stepsDictionary[" + index + "].Key"] = textBoxTitle;
data["stepsDictionary[" + index + "].Value"] = textboxValue;
});
//Makes ajax call to controller
$.ajax({
type: "POST",
data: data,
url: "/Home/ProcessStepsValues",
success: function (message) {
alert(message);
}
});
});
});
</script>
And then sends the data to controller
Controller.cs
[HttpPost]
public string ProcessStepsValues(Dictionary<string, string> stepsDictionary)
{
string resultMessage = string.Empty;
if (stepsDictionary != null)
{
resultMessage = "Dictionary data passes to controller successfully!";
}
else
{
resultMessage = "Something goes wrong, dictionary is NULL!";
}
return resultMessage;
}
Please refer the site for more details
https://alexkuznetsov.wordpress.com/2013/05/08/asp-net-mvc-pass-dictionary-data-from-view-to-controller/

Categories

Resources