How to send hidden ID value FormData using asp.net MVC? - c#

I need to pass Hidden ID value var genericID = $("#hdnGenericID").val(); to FromData.But i can't able to pass Id Value.
how to pass the hdnGenericID ID value to controller.
#Html.HiddenFor(model => item.GenericID, new { id = "hdnGenericID" })
cs.Html
<div class="uploading-container">
<div class="uploading-container-left">
<span class="btn btn-rounded btn-file">
<span>Choose file</span>
<input type="file" name="file" id="file">
</span>
</div><!--.uploading-container-left-->
<div class="uploading-container-right">
<div class="uploading-container-right-in">
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label semibold">Perview_Image</label>
<img id="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
<a id="remove" onclick="javascript:ClearFileUploadControl();" style="display: none; cursor: pointer;">Remove</a>
</fieldset>
</div>
<input type="submit" id="btnImageUpload" name="ImageUpload" value="Upload image" class="btn btn-rounded btn-inline btn-success" />
</div>
</div>
</div>
Image Upload:
$(function () {
$('#btnImageUpload').click(function () {
var data = new FormData();
var genericID = $("#hdnGenericID").val();
var files = $("#file").get(0).files;
if (files.length > 0) { data.append("HelpSectionImages", files[0]); }
else {
common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
return false;
}
var extension = $("#file").val().split('.').pop().toUpperCase();
if (extension != "PNG" && extension != "JPG" && extension != "GIF" && extension != "JPEG") {
common.showNotification('warning', 'Imvalid image file format.', 'top', 'right');
return false;
}
$.ajax({
url: '../Generic/SaveProfileImage',
type: "POST",
processData: false,
data: data,
dataType: 'json',
contentType: false,
success: function (data) {
if (data == true) { // if true (1)
setTimeout(function () {// wait for 1 secs(2)
location.reload(); // then reload the page.(3)
}, 1000);
}
},
error: function (er) { }
});
return false;
});
});
Controller:
[HttpPost]
public ActionResult SaveProfileImage()
{
try
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
var fileName = docId.ToString() + ".png";
var path = Path.Combine(Server.MapPath("~/UploadGenericImage/"), fileName);
filebase.SaveAs(path);
//return Json("File Saved Successfully.");
return Json(new { data = true});
}
else { return Json("No File Saved."); }
}
catch (Exception ex) { return Json("Error While Saving."); }
}

Change the script like this
$(function () {
$('#btnImageUpload').click(function () {
var data = new FormData();
var genericID = $("#hdnGenericID").val();
data.append("GenericID", genericID);
var files = $("#file").get(0).files;
if (files.length > 0) { data.append("HelpSectionImages", files[0]); }
else {
common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
return false;
}
var extension = $("#file").val().split('.').pop().toUpperCase();
if (extension != "PNG" && extension != "JPG" && extension != "GIF" && extension != "JPEG") {
common.showNotification('warning', 'Imvalid image file format.', 'top', 'right');
return false;
}
$.ajax({
url: '../Generic/SaveProfileImage',
type: "POST",
processData: false,
data: data,
dataType: 'json',
contentType: false,
success: function (data) {
if (data == true) { // if true (1)
setTimeout(function () {// wait for 1 secs(2)
location.reload(); // then reload the page.(3)
}, 1000);
}
},
error: function (er) { }
});
return false;
});
});
and change the controller like this
[HttpPost]
public ActionResult SaveProfileImage(string GenericID)
{
try
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(pic);
var fileName = docId.ToString() + ".png";
var path = Path.Combine(Server.MapPath("~/UploadGenericImage/"), fileName);
filebase.SaveAs(path);
//return Json("File Saved Successfully.");
return Json(new { data = true});
}
else { return Json("No File Saved."); }
}
catch (Exception ex) { return Json("Error While Saving."); }
}
then in controller you will be able to access the value of GenericID.

did you try using FormCollection parameter to controller action method i.e.
[HttpPost]
public ActionResult SaveProfileImage(FormCollection form,string GenericID)
{....
}
this form will have your hiddenfield value and can access hiddenfield like below
var hiddenFieldValue = form["hdnGenericID"] ..

Related

The view doesn't return from controller

I want to carry data by onclick function to the next page. All data is carried along with by giving parameter but it doesn't return View from the controller. Please help me. I'm stuck in here two days this is my school project.
OnClick button:
<div class="row">
<div class="col-sm-4"></div>
<button class='btn bg-blue next' onclick="checkamt(#Model.TotalAmt)">Next</button>
</div>
Controller:
public ActionResult ComfirmPay(int e = 0, string TaxType = null, int CurrentAmt = 0)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View("ComfirmPay");
}
Ajax:
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
alert('bad');
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
alert('good');
$.ajax({
cache: false,
url: '#Url.Action("ComfirmPay", "Home")',
data: { e: e, taxtype: taxtype, currentamt: currentamt },
beforeSend: function () {
},
success: function () {
},
complete: function () {
}
})
}
}
View:
<div class="col-md-9 col-xs-9">
<p class="text-muted">You have total <b class="text-green">#ViewBag.CurrentAmt</b> points</p>
</div>
Remove the ajax function and do this
window.location.href = "#Url.Action("ComfirmPay", "Home")" + "?e=" + e + "&taxtype=" + taxtype + "&currentamt=" + currentamt
The comment on this post explains a little more about why what you are trying to do does not work.
i think for your purpose there is no need of ajax call. you can use window.location.hrefas follows
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
window.location.href = '/Home/ComfirmPay?e='+e+'&taxtype='+taxtype+'&currentamt='+currentamt;
}
}
and in the controller
public ActionResult ComfirmPay(string e, string TaxType, string CurrentAmt)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View();
}

Posting files and model to controller in ASP.NET Core MVC6

I'm migrating a project from ASP.NET RC1 to ASP.NET Core 1.0.
I have a view that allows users to upload one of more files, which I post using Jquery Ajax. I also serialize and post some settings within the same post.
The following all worked in RC1 (and pre-asp.net core):
Js:
$('#submit').click(function () {
var postData = $('#fields :input').serializeArray();
var fileSelect = document.getElementById('file-select');
var files = fileSelect.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.each(postData, function (key, input) {
data.append(input.name, input.value);
});
var url = '/ajax/uploadfile';
$.ajax({
url: url,
type: "POST",
contentType: false,
processData: false,
cache: false,
data: data,
success: function (result) {
alert('success');
},
error: function () {
alert('error');
}
});
});
Controller:
public IActionResult UploadFile(UploadFileModel model)
{
var result = new JsonResultData();
try
{
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
//etc
}
}
}
So the above does not work anymore, no file uploaded and no model bound.
I managed to fix half the issues so now I can get the model to bind with the following code. However, the controller will still give me an exception on the Request.Files. I added the 'headers' property, and I used serializeObject (custom method). In the controller I added FromBody.
Js:
$('#submit').click(function () {
var postData = $('#fields :input').serializeArray();
var fileSelect = document.getElementById('file-select');
var files = fileSelect.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.each(postData, function (key, input) {
data.append(input.name, input.value);
});
var url = '/ajax/uploadfile';
$.ajax({
url: url,
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
processData: false,
cache: false,
data: serializeAndStingifyArray(data),
success: function (result) {
alert('success');
},
error: function () {
alert('error');
}
});
});
function serializeAndStingifyArray(array) {
var o = {};
var a = array;
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return JSON.stringify(o);
};
Controller:
[HttpPost]
public IActionResult UploadFile([FromBody]UploadFileModel model)
{
var result = new JsonResultData();
try
{
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
//etc
}
}
}
html:
<div id="file-list">
<input type="file" name="file" class="file-select" accept="application/pdf,application">
<input type="file" name="file" class="file-select" accept="application/pdf,application" />
</div>
I started from this article which has some code that is almost the same as yours Upload Files In ASP.NET Core 1.0 (see Ajax case).
That worked for me fine on 1.0.0, so I implemented your changes and what I saw is that it failed to send the files in the request (client side issue).
This is how the payload should look like when working ok using F12 in chrome: (not sure why the file contents are hidden by chrome).
A little debugging and you are passing wrong data to data.append
The fix is in this line
$(".file-select").each(function () { data.append($(this).val(), $(this).get(0).files[0]); i++; })
Full code:
$(document).ready(function () {
$("#submit").click(function (evt) {
var data = new FormData();
i = 0;
$(".file-select").each(function () { data.append($(this).val(), $(this).get(0).files[0]); i++; })
var postData = $('#fields :input');
$.each(postData, function (key, input) {
data.append(input.name, input.value);
});
$.ajax({
type: "POST",
url: "/ajax/uploadfile", // <--- Double check this url.
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was error uploading files!");
}
});
});
});
No need to use [FromBody] or serializeArray()
[HttpPost]
public IActionResult UploadFilesAjax(MyViewModel xxx )
{
This is my html, just in case:
<form method="post" enctype="multipart/form-data">
<div id="file-list">
<input type="file" name="file" class="file-select" accept="application/pdf,application">
<input type="file" name="file" class="file-select" accept="application/pdf,application" />
</div>
<div id="fields">
<input type="text" name="Email" />
</div>
<input type="button"
id="submit"
value="Upload Selected Files" />
</form>

Refresh page after POST

I have created a solution where I post an array of string to my controller.
The setup works fine but I have to manually refresh the page before I can see the results of my method.
How do I make the solution refresh the page after I posted?
My view (tree.html):
<form>
<textarea class="form-control auto-input-field" rows="10" cols="80" id="autoGenerateInputField" ng-model="fighterList" ng-list="/\n/" />
<input class="btn btn-primary" type="submit" ng-click="GenerateTournamentTree(data)" value="Generer kamptræ" />
</form>
My js (angular):
$scope.GenerateTournamentTree = function(matches){
var stringOfFighters = new Array();
var categoryId = $scope.CategoryId;
stringOfFighters = $scope.fighterList;
var postData = { fighters: stringOfFighters };
if (stringOfFighters != null) {
$.ajax({
type: "POST",
url: "/Api/Match/GenerateTournamentTree",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(stringOfFighters),
success: function (data) {
alert(data.Result);
},
dataType: "json",
traditional: true
});
} else {
$modal.open({
templateUrl: 'generateTreeMessage.html',
scope: $scope,
controller: function ($scope) {
$scope.ok = function () {
$scope.$dismiss();
}
$scope.cancel = function () {
$scope.$dismiss();
}
}
})
}
}
My controller:
[Route("api/Match/GenerateTournamentTree")]
public IHttpActionResult GenerateTournamentTree(List<String> fighters)
{
fighters.Shuffle();
var nodeTree = InsertNode(new TreeNode(), fighters);
var matches = new List<MatchRecord>();
GenerateMatch(matches, nodeTree);
foreach(var match in matches)
{
match.CategoryId = new Guid("425d750e-56bd-412c-8a48-38c2fbe5b24c");
match.EventId = 18;
}
db.Matches.AddRange(matches);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
throw;
}
//return CreatedAtRoute("DefaultApi", new { id = "18" }, fighters);
//I tried this but with no succes.
return Json(new { Result = fighters });
//this is only created to return something.
}

how to send upload control data to jquery ajax wihout plugins

I am trying to upload file/files to server through Ajax request in MVC, but the file is always returning null in the controller, can you please suggest the way to pass the file data in the ajax request?
<form method="post" enctype="multipart/form-data">
<div>
#Html.AntiForgeryToken()
<input type="file" name="file" id="files" multiple><br>
<input type="button" value="Upload File to Server" id="submit">
</div>
</form>
<script type="text/javascript">
$("#submit").click(function () {
var formData = $('#files').val();
alert(formData);
$.ajax({
url: 'home/index',
type: 'POST',
datatype: 'json',
enctype: "multipart/form-data",
data: { file: formData },
//processData: false, // Don't process the files
//contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
alert(data);
},
error: function () {
alert("failed");
}
});
});
</script>
[HttpPost]
[ActionName("Index")]
public ActionResult Index_Post(HttpPostedFileBase file)
{
string errormsg = string.Empty;
if (file != null)
{
// 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);
try
{
file.SaveAs(path);
errormsg = "uploaded";
return Json(fileName + errormsg);
}
catch
{
errormsg = "failed to upload";
return Json(fileName + errormsg);
}
}
}
else
{
errormsg = "No file selected";
return Json(errormsg);
}
return View();
}
}
Take normal button instead of submit button and try below code
$("#submit").click(function () {
var formData = new FormData();
var opmlFile = $('#myFile')[0];
formData.append("opmlFile", opmlFile.files[0]);
$.ajax({
url: 'home/index',
type: 'POST',
datatype: 'json',
enctype: "multipart/form-data",
data: formData ,
//processData: false, // Don't process the files
//contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
alert(data);
},
error: function () {
alert("failed");
}
});
});
});
and controller action :-
[HttpPost]
[ActionName("Index")]
public HttpResponseMessage Index()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();
// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
files.Add(filePath);
}
// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}

Change button status (MVC)

I wanna make twitter like microblog site which other users can follow my posts.
For that i made page with all currently registered users. In front of each name there is button to follow/unfollow user. (Like in Twitter)
View -
#{
ViewBag.Title = "Users";
}
#model MembershipUserCollection
#foreach (MembershipUser item in Model)
{
if(User.Identity.Name != item.UserName)
{
<li>#item.UserName
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
</li>
}
}
<script type="text/javascript">
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
</script>
Controller -
public ActionResult Index()
{
return View(Membership.GetAllUsers());
}
public void FollowUser(string id)
{
ViewData["test"] = "test";
var n = FollowingUser.CreateFollowingUser(0);
n.FollowingId = id;
n.FollowerId = User.Identity.Name;
string message = string.Empty;
var list = new List<FollowingUser>();
list = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == id select a).ToList();
if (list.Count() == 0)
{
try
{
db.AddToFollowingUsers(n);
db.SaveChanges();
}
catch (Exception ex)
{
message = ex.Message;
}
}
else
{
db.DeleteObject((from a in db.FollowingUsers where a.FollowerId == User.Identity.Name select a).FirstOrDefault());
db.SaveChanges();
}
}
FollowingUsers Table -
Now i wanna change button status on page load checking database whether he is already followed or not.
Ex- If user already followed it should display like below.
When you show this view to a user where this button is displayed, Load the status also, if the person is following or not.
public ActionResult Index()
{
var model = new MemberShipViewModel();
//We check here if the logged in user is already following the user being viewd
foreach(var member in Membership.GetAllUsers())
{
var user = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == member.UserName select a).FirstOrDefault();
model.Members.Add(new Member{UserName = member.UserName,IsFollowing=user!=null});
}
//This line will remove the logged in user.
model.Members.Remove(model.Members.First(m=>m.UserName==User.Identity.Name));
return view(model);
}
In your index view model, you need to make some changes.
#model MemberShipViewModel
#foreach (var item in Model)
{
<li>#item.UserName
if(!item.IsFollowing)
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
}
else
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="unfollow-user fg-button ui-state-default"/></span>
}
</li>
}
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
You need to write some javascript now. Nobody is going to write full software for you.
Seems you are missing very basic programming skills.
cheers

Categories