ASP.NET Upload file return its content - asp.net

I'm trying to upload a file then retrieve its content as JSon
My controller :
controller.cs
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
List<string> list = doStuff(file);
return Json(list);
}
My view :
view.cshtml
#using (Html.BeginForm("Upload", "Files", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" name="Upload" value="Upload" />
}
When I upload a file it propose me to download a JSON file, but what I want is to set a javascript variable with this JSON so I can use it directly on my webpage.

I believe that the best solution is to use an ajax form.
See the example below:
Controller:
[HttpPost]
public JsonResult Upload(HttpPostedFileBase file)
{
return Json(new { ReturnMessage = "Success!!!!!" + file.FileName});
}
View:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { #id="formUploadFile", #onsubmit = "return SubmitFormWithFile();" }))
{
#Html.TextBox("file", null, new { #type = "file", #id = "file" })
<button type="submit">Send</button>
}
Javascript:
function SubmitFormWithFile() {
var form = $("#formUploadFile");
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: new FormData(form[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
alert("Before Send");
},
success: function (dataResult) {
//set its variable here...
//the dataResult is returned json...
alert(dataResult.ReturnMessage);
},
error: function () {
alert("Error");
}
});
return false;
}

Related

Razor pages - updating label when the input changes

I want to display a label that shows an item's price, getting that price from the input box(and potentially calculating a new price based on another inputs such as checkbox). I want as soon as the user changes that value in the input, the controller to calculate everything with the new values.
How can I do that?
Thanks in advance!
You can use the keyup event to achieve this requirement. Below are examples of mvc and razor-pages.
Mvc
Home controller:
public IActionResult Test()
{
return View();
}
[HttpPost]
public IActionResult Test(int data)
{
//you can do your logic here
data++;
return new JsonResult(new { result = data });
}
Test View:
<input id="input" type="number" />
<div id="other"></div>
#section Scripts
{
<script>
$("#input").keyup(function () {
var data = $("#input").val();
$.ajax({
type: "POST",
url: "/home/test",
data: { "data": data },
dataType: "json",
success: function (response) {
$('#other').html(response.result);
}
});
});
</script>
}
Razor pages
In your startup,add
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
PageModel:
public class TestModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostInput(int data)
{
data++;
return new JsonResult (new { result=data});
}
}
Page
<input id="input" type="number" />
<div id="other"></div>
#section Scripts
{
<script>
$("#input").keyup(function () {
var data = $("#input").val();
$.ajax({
type: "POST",
url: "?handler=input",
data: { "data": data },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
success: function (response) {
$('#other').html(response.result);
}
});
});
</script>
}
Test result:

how can I get the selected value of checkboxlist and passed that value from view to controller using jquery

view:
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<li><input type="checkbox" name="qualitycheck"/><span>item.qualityName</span></li>
}
}
Controller:
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
}
I want to pass multiple selected value to the controller
Your View Code Should be :
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="qualitycheck"
value="#item.qualityName" /> #item.qualityName
</label>
</div>
}
#*<div class="form-group text-center">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>*#
}
For without Submit button you have to add jQuery Code to call controller action :
$( document ).ready(function() {
$(":checkbox").change(function() {
if(this.checked) {
var qualitycheck_data = { 'qualitycheck': [] };
$('input:checked').each(function ()
{
if(this.name == 'qualitycheck') qualitycheck_data['qualitycheck'].push($(this).val());
});
var path = "/Health/Searchbyquality";
$.ajax({
url: path, type: "POST", cache: "false",
dataType: "json", contentType: "application/json; charset=utf-8",
data: JSON.stringify(qualitycheck_data),
traditional: true,
converters: {'text json': true}
}).success(function (responseText) {
//Success result
window.location.assign(responseText);
}).error(function (responseText){
swal("Error!", "Test 1", "error");
});
//swal("Error!", "Test 2", "error");
}
});
});
And your Controller Action :
[HttpPost]
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
return View("");
}
cheers !!

pass parameter from View to Controller in asp mvc

I am trying to pass parameter from view to controller,
This is my View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#foreach (var pricedetails in ViewBag.PriceTotal)
{
<div style="text-align:center; clear:both ">
<h5 class="product-title">#pricedetails.Title</h5>
</div>
<div class="product-desciption" style="height:40px">#pricedetails.Descriptions</div>
<p class="product-desciption product-old-price"> #pricedetails.PricePoints</p>
<div class="product-meta">
<ul class="product-price-list">
<li>
<span class="product-price">#pricedetails.PricePoints</span>
</li>
<li>
<span class="product-save">Get This Free</span>
</li>
</ul>
<ul class="product-actions-list">
<input type="submit" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />
</ul>
</div>
}
}
my action method:
On submit it reaches the Action Method, but I am not able to get the PriceId for each Price
[HttpPost]
public ActionResult Index(int id=0) // here PriceId is not passed on submit
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Content("<script language='javascript' type='text/javascript'>alert('You are not elgible');</script>");
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('You are elgible');</script>");
}
return View("Index");
}
Url Routing:
routes.MapRoute(
name: "homeas",
url: "Index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
May I know what wrong I am doing ?
Please use the following in your cshtml page
#foreach (var item in Model)
{
#Html.ActionLink(item.PriceDetails, "GetGift", new { priceID = item.priceID }, new { #class = "lnkGetGift" })
}
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a.lnkGetGift").on("click", function (event) {
event.preventDefault();
$.get($(this).attr("href"), function (isEligible) {
if (isEligible) {
alert('eligible messsage');
}
else
{
alert('not eligible messsage');
}
})
});
});
</script>
and in controller
[HttpGet]
public JsonResult GetGift(int priceID)
{
List<Price_T> priceimg = (from x in dbpoints.Price_T
select x).Take(3).ToList(); ;
ViewBag.PriceTotal = priceimg;
var allpoint = singletotal.AsEnumerable().Sum(a => a.Points);
var price = from x in dbpoints.Price_T
where x.PriceId == id
select x.PricePoints;
int pricepoint = price.FirstOrDefault();
if (allpoint < pricepoint)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Please change your parameters according to the method param and price entity
Hope this helps.
I suggest you get rid of the Html.BeginForm(). Just leave the for...loop and define your "Get Gift" button like this:
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(pricedetails.PriceId))'" />
Then, at the bottom of the view file where the Get Gift button is located, define some JavaScript:
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("Index", "Home")',
data: { priceId: priceId },
contentType : "json",
success:function(data){
// Do whatever in the success.
},
error:function(){
// Do whatever in the error.
}
});
</script>
By using an ajax call to get the gift data, you don't have to submit anything. This makes things a lot easier in your case. Pressing the Get Gift button simply makes an ajax call.
I don't have time to try this out myself, but hopefully the above example should get you up and running.
EDIT:
I've managed to sneak in some time to come up with an example.
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var items = new List<int>();
items.Add(1);
items.Add(2);
items.Add(3);
return View(items);
}
public ActionResult GetGift(int priceId)
{
return RedirectToAction("Index"); // You'll be returning something else.
}
}
View
#model List<int>
#foreach (var price in Model)
{
<input type="button" id='giftid' name='giftid' value="Get Gift" onclick="getGift(#(price))" />
}
<script type="text/javascript">
function getGift(priceId) {
$.ajax({
type: 'GET',
url: '#Url.Action("GetGift", "Home")',
data: { priceId: priceId },
contentType: "json",
success: function(data) {
// Do whatever in the success.
},
error: function() {
// Do whatever in the error.
}
});
}
</script>
Hope this helps you.
I think you should correct here
<input type="button" name='giftid' value="Get Gift"
onclick="location.href='#Url.Action("Index", new { id = pricedetails.PriceId })'" />

HTML not being generated in View's foreach loop using MVC 4

I am using AJAX to call an ActionResult and return a list of files. The data is stored in a dictionary object in the model then passed to the view. I have a foreach loop in the view that checks to see if the object is null. If not, it loops through the dictionary and produces table rows for each key/value pair. The problem is, the HTML is never generated and nothing is displayed. Using Firebug I have stepped through the entire process and everything is returned as it should be. Any help finding out why would be appreciated.
The AJAX:
function () {
$.ajax({
url: '#Url.Action("GetExpenseReportUploads", "MyExpenseReports")',
type: "GET",
async: true,
cache: false,
data: { DirectoryName: "ER_#=EPR_ID#" },
success: function() {
alert("success!");
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
}
The Controller:
public ActionResult GetExpenseReportUploads(string DirectoryName)
{
ExpenseReport.MVC.Models.MyExpenseReports model = new MyExpenseReports();
IEnumerable<string> fileArray = Directory.EnumerateFiles(Server.MapPath("~/Files/" + DirectoryName + "/")).Select(fn => "~/Files/" + DirectoryName + "/" + Path.GetFileName(fn));
//model.EPR_Uploads = Path.GetFileName(fileArray);
Dictionary<string, string> fileNames = new Dictionary<string, string>();
foreach (string filePath in fileArray)
{
string fileName = Path.GetFileName(filePath);
fileNames.Add(filePath, fileName);
model.EPR_Uploads = fileNames;
}
model.EPR_Upload_DirectoryName = DirectoryName;
return View(model);
}
The View:
<table>
#if (Model.EPR_Uploads != null)
{
foreach (KeyValuePair<string, string> upload in Model.EPR_Uploads)
{
<tr>
<td>
#using (Html.BeginForm("DeleteUpload", "MyExpenseReports", FormMethod.Post))
{
#Html.HiddenFor(m => m.FileId, new { #value = #upload.Value })
#Html.HiddenFor(m => m.EPR_Upload_DirectoryName)
}
<input type="submit" id="DeleteUploadBtn" value="Delete File" formaction="#Url.Action("DeleteUpload", "MyExpenseReports", new { FileId = #upload.Value, EPR_ID = "#=EPR_ID#", DirectoryName = Model.EPR_Upload_DirectoryName })" />
</td>
<td>
</td>
<td>
</td>
</tr>
}
}
You're mixing server-side processing and client-side processing. If you want the table to be built after your client-side AJAX call, you don't want to use the server-side model (Model.EPR_Uploads).
Instead, use a post-load client call to build the HTML. For example:
function () {
$.ajax({
url: '#Url.Action("GetExpenseReportUploads", "MyExpenseReports")',
type: "GET",
async: true,
cache: false,
data: { DirectoryName: "ER_#=EPR_ID#" },
success: function(data, textStatus, jqXHR) {
$("#tableId").append("<tr><td>" + data.EPR_Upload_DirectoryName + "</td></tr>";
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
You'll need to change your Controller to return data in JSON so you can properly parse it on the client side.
Hopefully this helps.

Partial view render on button click

I have Index view:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<title>MsmqTest</title>
</head>
<body>
<div>
<input type="submit" id="btnBuy" value="Buy" onclick="location.href='#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })'" />
<input type="submit" id="btnSell" value="Sell" onclick="location.href='#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })'" />
</div>
<div id="msmqpartial">
#{Html.RenderPartial("Partial1", Model); }
</div>
</body>
</html>
and partial:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<p>
Items to buy
#foreach (var item in Model.ItemsToBuy)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
<p>
<a>Items Selled</a>
#foreach (var item in Model.ItemsSelled)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
And controller:
public class MsmqTestController : Controller
{
public MsmqData data = new MsmqData();
public ActionResult Index()
{
return View(data);
}
public ActionResult BuyItem()
{
PushIntoQueue();
ViewBag.DataBuyCount = data.ItemsToBuy.Count;
return PartialView("Partial1",data);
}
}
How to do that when i Click one of button just partial view render, now controller wants to move me to BuyItem view ;/
The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:
<script src="#Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:
<input type="button" value="Buy" data-url="#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />
and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:
$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});
or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:
#Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
#Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
and if you want buttons instead of anchors you could use AJAX forms:
#using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
#using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.
Maybe not the solution you were looking for but, I would forget about partials and use Javascript to call the server to get the data required and then return the data to the client as JSON and use it to render the results to the page asynchronously.
The JavaScript function;
var MyName = (function () {
//PRIVATE FUNCTIONS
var renderHtml = function(data){
$.map(data, function (item) {
$("<td>" + item.whateveritisyoureturn + "</td>").appendTo("#msmqpartial");
});
};
//PUBLIC FUNCTIONS
var getData = function(val){
// call the server method to get some results.
$.ajax({ type: "POST",
url: "/mycontroller/myjsonaction",
dataType: "json",
data: { prop: val },
success: function (data) {
renderHtml();
},
error: function () {
},
complete: function () {
}
});
};
//EXPOSED PROPERTIES AND FUNCTIONS
return {
GetData : getData
};
})();
And on the Server....
public JsonResult myjsonaction(string prop)
{
var JsonResult;
// do whatever you need to do
return Json(JsonResult);
}
hope this helps....

Resources