why is file.PostedFile is always null - c#

I need to upload images to my data base, and in order to that I need to bring them to the server side.
The only problem is the file is always null and I can't use it.
html:
<form id="signUpForm" runat="server" action="signUp.aspx" method = "get" name = "signUp"
enctype="multipart/form-data" onsubmit = "return validateSignUp();">
<div id = "input">
<table>
<tr>
<td class = "description">*profile image: </td>
<td class = "input" id = "inputProfileImage"><input type = "file" name = "profileImage" accept = "image/png, image/jpeg, image/jpg" id = "profileImage" runat="server"/>
<div class = "warning" id = "warnProfileImage"></div>
</td>
</tr>
<tr>
<td><input type = "submit" value = "sign up"/></td>
<td><input type = "reset" value = "reset"/></td>
</tr>
</table>
</div>
<div id = "showInfo">
<table>
<tr><td class = "description">profile image:</td><td class = "input"><img src = "defaultProfileImages/defaultProfileImage1.png" id = "showProfileImage" name="showProfileImage" runat="server"/></td></tr>
<tr><td><input type = "submit" name = "submit" value = "confirm"/></td></tr>
</table>
</div>
</form>
c#:
if (Request.QueryString["submit"] != null)
{
string path = "";
if ((profileImage.PostedFile != null) && (profileImage.PostedFile.ContentLength > 0))
{
string fn = System.IO.Path.GetFileName(profileImage.PostedFile.FileName);
string SaveLocation = Server.MapPath("Temp") + "\\" + fn;
path = SaveLocation;
try
{
profileImage.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
//Note: Exception.Message returns a detailed message that describes the current exception.
//For security reasons, we do not recommend that you return Exception.Message to end users in
//production environments. It would be better to put a generic error message.
}
}
User user = new User(Libary.convertFile(path));
UserService userService = new UserService();
userService.InsertUser(user);
Response.Redirect("homePage.aspx");
Response.End();
}
*I deleted all the lines that doesn't has anything to do with the file.

Try to use HttpPostedFileBase instead of PostedFile for quick issue resolve.

Turn out you can't get a file in the server side if you are using a "get" method in your form. So you just need to change the form method to "post".
HTML:
<form id="signUpForm" runat="server" action="signUp.aspx" method = "post" name = "signUp" enctype="multipart/form-data" onsubmit = "return validateSignUp();">
<table>
<tr>
<td class = "description">phone number: </td>
<td class = "input" id = "inputPhoneNumber"><input type = "tel" pattern="[0-9]{3}-[0-9]{7}" name = "phoneNumber" id = "phoneNumber" runat="server"/><div class = "warning" id = "warnPhoneNumber"></div></td>
</tr>
<tr>
<td class = "description">*profile image: </td>
<td class = "input" id = "inputProfileImage"><input type = "file" name = "profileImage" accept = "image/png, image/jpeg, image/jpg" id = "profileImage" runat="server"/>
<div class = "warning" id = "warnProfileImage"></div>
</td>
</tr>
<tr>
<td><input type = "submit" value = "sign up"/></td>
<td><input type = "reset" value = "reset"/></td>
</tr>
</table>
</form>
You just need to know that you can't use "Request" if your from method is "post", So I just used one of the others input's in the form.
C#:
using System.Drawing;
using System.IO;
public partial class signUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if ((phoneNumber.Value != null) && (phoneNumber.Value.Length > 0))
{
string path = "";
bool deleteFile = false;
if ((profileImage.PostedFile != null) && (profileImage.PostedFile.ContentLength > 0))
{
path = Libary.save(profileImage.PostedFile, Server);
deleteFile = true;
}
User user = new User(Libary.convertFile(path));
UserService userService = new UserService();
userService.InsertUser(user);
Response.Redirect("homePage.aspx");
Response.End();
if ((deleteFile) && (File.Exists(path))){File.Delete(path);}
}
}
}
*Libary.save(HttpPostedFile file, HttpServerUtility Server) function is just saving the file and returning the path to it.

Related

How to display the alert message and redirect to index page in in ASP.NET MVC

i have a button in index.html , when press the button will be first to check validation , if You don't have permission, How to display the alert message and redirect to index page in ASP.NET ?
I have try to using return Redirect("Index"); ,but can't show alert message。
please anyone can tell me How to do this?
view/index.html,
<table style="width: 100%;">
<tr>
<td>
<label class="features-title">#ViewBag.Title</label>
#if (rolestr.Contains("Maintain"))
{
#*<p>*#
#Html.ActionLink("Apply", "Create", null, new { #class = "btn btn-primary " })
#*</p>*#
}
</td>
<td class="text-right">
</td>
</tr>
</table>
my controller.cs,
[RoleFilters(Controller = "HA03", Action = "Index", Role = "Maintain")]
public ActionResult Create()
{
StayDormApplication DormApplication = new StayDormApplication();
DormApplication.Sdate = DateTime.Now.AddDays(1);
DormApplication.Edate = DateTime.Now.AddDays(2);
string LoginAccount = Utility.Encryption(User.Identity.Name);
var Member = _db.Members.FirstOrDefault(x => x.Account == LoginAccount);
ViewBag.Name = Utility.Decryption(Member.Name);
ViewBag.AppType = Member.TradeName;
DateTime now = DateTime.Now;
var RoomInfo = _db.DormApplications.Where(p => p.Poster == username && now > p.Sdate && now <p.Edate).FirstOrDefault();
if (RoomInfo == null)
{
Response.Write("<script>alert('You don't have permission to access /register.'); </script>");
return Redirect("Index");
}
return View(DormApplication);
}

Server side validation for the user Input

I have a table in the web application from where the users can make orders. The table shows the Quantity that is available and we need to let users enter the quantity they need like below
when the Order button is clicked I want to validate if the user is entering the Quantity Required is greater than the Quantity Avail. Every time the Order button is clicked it calls the Controller to retrieve the data and check against the quantity. The view is like below
#model JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel
#{
ViewData["Title"] = "Index";
}
<h3>Order Surplus Mouse</h3>
<div class="col-md-9">
<table class="table">
<thead>
<tr>
<th>
Strain ID
</th>
<th>
Strain Name
</th>
<th>
Quantity Avail
</th>
<th>
Room Number
</th>
<th>
Quantity Required
</th>
<th></th>
</tr>
</thead>
<tbody>
#{var custID = Model.CustomerData; }
#foreach (var item in Model.Inventorys)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.StrainId)
</td>
<td>
#Html.DisplayFor(modelItem => item.StrainName)
</td>
<td>
#Html.DisplayFor(modelItem => item.QuantityAvailable)
</td>
<td>
#Html.DisplayFor(modelItem => item.RoomNumber)
</td>
<td>
<form method="post"
asp-controller="Inventories"
asp-action="OrderItem">
<row>
<column>
<input type="text" id="quantityReq" name="quantityReq" value=#item.QuantityReq size="4" />
<input type="hidden" id="customerID" name="customerID" value="#custID.CustomerId" />
<input type="hidden" id="invetoryID" name="invetoryID" value="#item.InventoryId" />
<button type="submit" style="border: none; background-color: transparent; color: #1a0dab "><u>Order</u></button>
</column>
</row>
</form>
</td>
</tr>
}
</tbody>
</table>
#{
var prevDisabled = !Model.Inventorys.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.Inventorys.HasNextPage ? "disabled" : "";
}
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.Inventorys.PageIndex - 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #prevDisabled"> Previous </a>
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.Inventorys.PageIndex + 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #nextDisabled"> Next </a>
</div>
</div>
And Controller action I am calling when clicking on the button is
public async Task<IActionResult> OrderItem(int? customerID, int? invetoryID, int quantityReq)
{
if (customerID == null || invetoryID == null || quantityReq == 0)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(invetoryID);
if (quantityReq <= intData.QuantityAvailable)
{
MouseOrder mo = new MouseOrder();
mo.CustomerId = (int)customerID;
mo.OrderDate = DateTime.Now;
mo.SamaccountName = "dvella";
_context.Add(mo);
await _context.SaveChangesAsync();
InventoryOrder io = new InventoryOrder();
io.OrderId = mo.MouseOrderId;
io.OrderQuantity = quantityReq;
io.InventoryId = (int)invetoryID;
_context.Add(io);
await _context.SaveChangesAsync();
intData.QuantityAvailable = intData.QuantityAvailable - quantityReq;
_context.Update(intData);
await _context.SaveChangesAsync();
}
else if (quantityReq > intData.QuantityAvailable){
}
return RedirectToAction("Index", "Inventories", new { id = customerID });
}
Get action in the Controller is like below
// GET: Inventories
public async Task<IActionResult> Index(int? id, string sortOrder, string searchString,
int? pageNumber, string currentFilter)
{
if (id == null)
{
return NotFound();
}
ViewData["StockParam"] = String.IsNullOrEmpty(sortOrder) ? "st_desc" : "";
ViewData["CurrentFilter"] = searchString;
ViewData["CurrentSort"] = sortOrder;
if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}
var inventories_data = from s in _context.Inventories
where s.QuantityAvailable >0
select s;
if (!String.IsNullOrEmpty(searchString))
{
inventories_data = inventories_data.Where(s => s.StrainCode.Contains(searchString));
}
switch (sortOrder)
{
case "st_desc":
inventories_data = inventories_data.OrderByDescending(s => s.StrainCode);
break;
default:
inventories_data = inventories_data.OrderBy(s => s.StrainCode);
break;
}
int pageSize = 15;
Customer custData = await _context.Customers.FindAsync(id);
var inventories = await PaginatedList<Inventory>.CreateAsync(inventories_data.AsNoTracking(), pageNumber ?? 1, pageSize);
var model = new CustomerInventoryCollectionDataModel
{
CustomerData = custData,
Inventorys = inventories
};
return View(model);
}
Model Class is like
public class CustomerInventoryCollectionDataModel
{
public Customer CustomerData { get; set; }
public PaginatedList<Inventory> Inventorys { get; set; }
}
Where the Inventory Class is like
public partial class Inventory
{
public string StrainId { get; set; }
public string StrainName { get; set; }
public int QuantityAvailable { get; set; }
public string RoomNumber { get; set; }
public int InventoryId { get; set; }
[NotMapped]
public int? QuantityReq { get; set; }
}
I am developing a web application for the first time using the .NET Core with EF and kind of stuck with this. Please Suggest me how can I handle the validation here. I am here not so particular where the validation message should be shown but a way to notify the users to enter the correct number. I appreciate all the help
****EDIT ****
I see the error like
When I enter less or more than the the Quantity Available it is not doing anything, in the devtools I see the error like the screenshot
Uncaught SyntaxError: Function statements require a function name
Before pressing the Buy Now button the URL is like https://localhost:44330/Inventories/Index/460 Any after I pressed the https://localhost:44330/Inventories/Index/460#
I am not able to troubleshoot more , kind of stuck here
try this. Since it is using ajax I removed a form and a submit button
#model JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel
#{
ViewData["Title"] = "Index";
}
<h3>Order Surplus Mouse</h3>
<table>
<thead>
<tr>
<th style="padding-right:1em">
Strain ID
</th>
<th style="padding-right:1em">
Strain Name
</th>
<th style="padding-right:1em">
Room
</th>
<th style="padding-right:1em">
Quantity Avail
</th>
<th>
Quantity Required
</th>
<tbody>
#foreach(var item in Model.Inventorys)
{
<tr>
<td />
<td />
<td />
<td />
<td style="padding-right:1em">
<input type="text" class="text-danger float-right" style="border:none;font-size: smaller" id="#("errorMessage"+#item.InventoryId)" readonly />
</td>
</tr>
<tr style="padding-left:2em">
<td>
#Html.DisplayFor(modelItem => item.StrainId)
</td>
<td>
#Html.DisplayFor(modelItem => item.StrainName)
</td>
<td>
#Html.DisplayFor(modelItem => item.RoomNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.QuantityAvailable)
</td>
<td>
<row>
<column>
<input type="text" style="text-align:right;padding-right:1em" id="#("quantityReq"+#item.InventoryId)" name="quantityReq" value="#item.QuantityReq" />
</column>
<column>
<input type="hidden" id="#("customer"+#item.InventoryId)" name="customerID" value="#Model.CustomerData.Id" />
<input type="hidden" id="#("inventory"+#item.InventoryId)" name="invetoryID" value="#item.InventoryId" />
Buy now
</row>
</td>
</tr>
}
</tbody>
</table>
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".buyNow", (function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var id=$(this).data("id");
onBuyNow(id);
}));
function onBuyNow(id) {
$("#errorMessage" + id).val("");
var quantityReq = $("#quantityReq"+id).val();
var customerId = $("#customer"+id).val();
var data = {
customerId: customerId,
quantityReq: quantityReq,
inventoryId: id
};
$.ajax({
url: '#Url.Action("OrderItem", "Inventories")',
dataType: 'json',
type: 'POST',
data: data,
success: function (result) {
if (result.status !== "Ok") {
$("#errorMessage" + result.inventoryId).val("available only " + result.available);
}
else {
var url = '#Url.Action("Index", "Inventories")';
url=url++"?id="+customerId;
alert("url: " + url);
window.location.href = url;
};
error: function (error) {
alert("error");
}
});
};
}
});
</script>
}
action
public async Task<ActionResult> OrderItem(int? customerID, int? inventoryID, int quantityReq)
{
if (customerID == null || invetoryID == null || quantityReq == 0)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(inventoryID);
if (quantityReq <= intData.QuantityAvailable)
{
... your code
}
else if (quantityReq > intData.QuantityAvailable){
return Ok( new { status = "NotAvailable", inventoryId=inventoryId, available = intData.QuantityAvailable} );
}
return Ok(new { status="Ok" } );
}
and the bottom of a body section of your layout should have
<script src="~/lib/jquery/dist/jquery.min.js"></script>
#await RenderSectionAsync("Scripts", required: false)

Model is null when url.action is called in asp.net

My model have List products which get from database.
When index view loaded, i get the variable from input of user, then model get varible, and return view OutputTableAsync. After view loaded, i click link "Export Excel", in debug mode, List products is null.
My view:
<body>
#if (Model != null)
{
var products = Model.products.Products;
Export Excel
<table border="1" style="width: 100%">
<thead>
<tr>
<th>Model</th>
<th>Price</th>
<th>Link</th>
<th>ImageUrl</th>
</tr>
</thead>
<tbody>
#foreach (var product in Model.products.SortProduct())
{
<tr id="i">
<td align="center">#product.Model</td>
<td align="center">#product.FormatPrice()</td>
<td align="center">#product.Link</td>
<td align="center"><img src="#product.ImageUrl" style="width : 200px; height:200px ;" id="#product.ImageUrl" /></td>
</tr>
}
</tbody>
</table>
}
</body>
ExportToExcel method in controller:
public void ExportToExcel(List<Product> products)
{
ExcelPackage pck = new ExcelPackage();
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Products");
ws.Cells["A1"].Value = "Model";
ws.Cells["B1"].Value = "Price";
ws.Cells["C1"].Value = "Link";
ws.Cells["D1"].Value = "ImageLink";
int rowstart = 2;
foreach(var item in products)
{
ws.Cells[string.Format("A{0}", rowstart)].Value = item.Model;
ws.Cells[string.Format("B{0}", rowstart)].Value = item.Price;
ws.Cells[string.Format("C{0}", rowstart)].Value = item.Link;
ws.Cells[string.Format("D{0}", rowstart)].Value = item.ImageUrl;
rowstart++;
}
ws.Cells["A:AZ"].AutoFitColumns();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment: filename=" + "ExcelFile.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}
According to accepted answer here you can not pass complex type through Url.Action
I would pass serialized version of object in this situation.

Angular Application code not checking username and Password from wcf service

I am consuming wcf REST Service into Angular JS Application. I am creating user Login System by using Angular Js Application . I have some stored user information like username and password into Sql database. The Passwords are Encrypted. I am using POST Method to cheek your name and password from sql Database with wcf service , if the username and password is correct the I want to redirect user into welcome page else user information is wrong I want to display message username or password id wrong . But when I clicked the login button its always redirect to Welcome Page without checking username and password.
Here is Interface .
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "/AuthenticateUser")]
bool AuthenticateUser(UserLogin userLogin);
Here is Implementation ..
public bool AuthenticateUser(UserLogin userLogin)
{
// ConfigurationManager class is in System.Configuration namespace
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
// SqlConnection is in System.Data.SqlClient namespace
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spAuthenticateUser", con);
cmd.CommandType = CommandType.StoredProcedure;
//Formsauthentication is in system.web.security
string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(userLogin.Password, "SHA1");
//sqlparameter is in System.Data namespace
SqlParameter paramUsername = new SqlParameter("#UserName", userLogin.Username);
SqlParameter paramPassword = new SqlParameter("#Password", encryptedpassword);
cmd.Parameters.Add(paramUsername);
cmd.Parameters.Add(paramPassword);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int RetryAttempts = Convert.ToInt32(rdr["RetryAttempts"]);
if (Convert.ToBoolean(rdr["AccountLocked"]))
{
return true;
}
else if (RetryAttempts > 0)
{
int AttemptsLeft = (4 - RetryAttempts);
//lblMessage.Text = "Invalid user name and/or password. " +
// AttemptsLeft.ToString() + "attempt(s) left";
}
else if (Convert.ToBoolean(rdr["Authenticated"]))
{
return true;
}
}
return false;
}
}
Here is Script code .
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Username = "";
$scope.Password = "";
}
$scope.login = function () {
var User = {
Username: $scope.Username,
Password: $scope.Password,
};
if ($scope.OperType === 1) {
var promisePost = myService.AuthenticateUser(User);
promisePost.then(function (pl) {
$scope.Id = pl.data.Id;
window.location.href = "/Login/WelcomePage";
ClearModels();
}, function (err) {
$scope.msg = "Password Incorrect !";
console.log("Some error Occured" + err);
});
}
};
}]);
app.service("myService", function ($http) {
// Create new record
this.AuthenticateUser = function (User) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/AuthenticateUser", JSON.stringify(User));
}
})
Here is the HTML code..
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/RegistrationScript/LoginScript.js"></script>
</head>
<body>
<table id="tblContainer" data-ng-controller="Web_Client_Controller">
<tr>
<td>
</td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Username</span>
</td>
<td>
<input type="text" id="username" data-ng-model="Username" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Password</span>
</td>
<td>
<input type="password" id="password" required data-ng-model="Password" require="" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="Login" value="Login" data-ng-click="login()" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Here is the screen shot when I run the application.
Any Help or suggestion will he highly appreciated.

How to run controller action after user clicks button in Jquery dialog, code must loop though all records so user can accept or reject

I am battling with some code in MVC, I managed to pass data form controller to a Jquery dialog widget, now i need to know how to return back to the controller depending on whether the user accepted or rejected the record. There is a list of records I upload as CSV onto MVC View, I then have a button called Validate Claims which calls a stored procedure to validate records, when validate claims is clicked a dialog pops up, with the response from the controller ViewBag passed, I want to then based on the validation response enable user to accept or reject record, when user accepts record it must save it to db then move to the next record. How can I do this in MVC JQuery, please assist.
Please see my code below:
Here is my View Code
#{
ViewBag.Title = "Home Page";
}
#*<link href="~/Content/jquery-ui.css" rel="stylesheet" />*#
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js"></script>
<link href="~/Content/themes/base/dialog.css" rel="stylesheet" />
#*<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>*#
#using CSVSupplierClaims.Models
#model List<CSVSupplierClaims.Models.SupplierClaimsUploadDisplayList>
<input type="submit" id="validateClaims" value="Validate Claims" size="5" />
<input type="submit" value="Import Claims to CRM" size="5" />
<div id="dialog" title="Supplier Claims Validation">
Claims Upload Confirmation
<p>
<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
<table id="users" class="ui-widget ui-widget-content" height="100" width="100" border="1">
<thead>
<tr class="ui-widget-header ">
<th style="width:70%">ST Key</th>
<th style="width:70%">Supplier Claim</th>
<th style="width:70%">System Cost</th>
<th style="width:70%">Orig Inv</th>
</tr>
</thead>
<tbody>
<tr>
<td>#ViewBag.ST_Key</td>
<td>#ViewBag.SupplierClaim</td>
<td>#ViewBag.OrigInv</td>
<td>#ViewBag.Error</td>
<td>#ViewBag.SystemCost</td>
</tr>
</tbody>
</table>
</p>
</div>
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
autoOpen: false
});
$("#validateClaims").click(function () {
$("#dialog").dialog("open", "resizable");
$("#dialog").dialog({
resizable: true,
height: 300,
width:500,
modal: true,
closeOnEscape: true,
buttons: {
"Accept Claim Record": function (){
$(this).dialog("close");
$(this).empty();
},
"Reject Claim Record": function () {
$(this).dialog("close");
}
}
});
});
});
</script>
<table>
<tr>
<th>Action</th>
<th>LineNo</th>
<th>TotalClaim</th>
<th>ClaimReference</th>
<th>Currency</th>
</tr>
#if (Model != null)
{
foreach (var c in Model)
{
<tr>
<td>#c.Action</td>
<td>#c.LineNo</td>
<td>#c.TotalClaim</td>
<td>#c.ClaimReference</td>
<td>#c.Currency</td>
</tr>
}
}
</table>
#Html.ValidationMessage("Error")
<form action="" method="post" enctype="multipart/form-data">
<table style="margin-top:150px">
<tr>
<td>
<label for="file"> Filename</label>
</td>
<td>
<input type="file" name="file" id="file" />
</td>
<td>
<input type="submit" value="Upload" />
</td>
</tr>
</table>
Here is my Controller Code
using CsvHelper;
using CSVSupplierClaims.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Crm;
using System.Data.SqlClient;
using System.Data;
namespace CSVSupplierClaims.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(HttpPostedFileBase file)
{
string path = null;
List<SupplierClaimsUploadDisplayList> supplierClaimsData = new List<SupplierClaimsUploadDisplayList>();
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = AppDomain.CurrentDomain.BaseDirectory + "upload\\" + fileName;
file.SaveAs(path);
var csv = new CsvReader(new StreamReader(path));
var supplierList = csv.GetRecords<SupplierClaimsUpload>();
foreach (var supplier in supplierList)
{
SupplierClaimsUploadDisplayList supplierUploadDisplay = new SupplierClaimsUploadDisplayList();
supplierUploadDisplay.Action = supplier.Action;
supplierUploadDisplay.LineNo = supplier.LineNo;
supplierUploadDisplay.TotalClaim = supplier.TotalClaim;
supplierUploadDisplay.ClaimReference = supplier.ClaimReference;
supplierUploadDisplay.Currency = supplier.Currency;
supplierClaimsData.Add(supplierUploadDisplay);
}
}
}
catch
{
ViewData["error"] = "Uplaod failed";
}
Supplier_Claim_Upload_Result supplierClaimUplaod = new Supplier_Claim_Upload_Result();
var sqlConnection = "data source=WMVSQL02;initial catalog=Embrace;integrated security=True;";
using (SqlConnection conn = new SqlConnection(sqlConnection))
{
try
{
foreach (var claim in supplierClaimsData)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 60;
SqlDataReader reader;
cmd.CommandText = "CRM.Supplier_Claim_Upload";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Invoice", SqlDbType.NVarChar).Value = claim.LineNo;
cmd.Parameters.Add("#Amount", SqlDbType.NVarChar).Value = claim.TotalClaim;
cmd.Connection = conn;
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
supplierClaimUplaod.ST_Key = reader["ST_Key"].ToString();
if (supplierClaimUplaod.SupplierClaim != null)
{
supplierClaimUplaod.SupplierClaim = reader["Supplier_Claim"].ToString();
}
else if (supplierClaimUplaod.SupplierClaim == null && supplierClaimUplaod.OrigInv == null && supplierClaimUplaod.SystemCost == null)
{
if (supplierClaimUplaod.Error != null)
{
supplierClaimUplaod.Error = reader["Error"].ToString();
}
else if (supplierClaimUplaod.Error == null)
{
supplierClaimUplaod.SupplierClaim = "No value";
}
}
if (supplierClaimUplaod.OrigInv != null)
{
supplierClaimUplaod.OrigInv = reader["Orig_Inv"].ToString();
}
else if (supplierClaimUplaod.OrigInv == null)
{
if (supplierClaimUplaod.Error != null)
{
supplierClaimUplaod.Error = reader["Error"].ToString();
}
else if (supplierClaimUplaod.Error == null)
{
supplierClaimUplaod.OrigInv = "No value";
}
}
if (supplierClaimUplaod.SystemCost != null)
{
supplierClaimUplaod.SystemCost = reader["System_Cost"].ToString();
}
else if (supplierClaimUplaod.SystemCost == null)
{
if (supplierClaimUplaod.Error != null)
{
supplierClaimUplaod.Error = reader["Error"].ToString();
}
else if (supplierClaimUplaod.Error == null)
{
supplierClaimUplaod.SystemCost = "No Value";
}
}
}
if (supplierClaimUplaod != null)
{
ViewBag.ST_Key = supplierClaimUplaod.ST_Key;
ViewBag.SupplierClaim = supplierClaimUplaod.SupplierClaim;
ViewBag.OrigInv = supplierClaimUplaod.OrigInv;
ViewBag.Error = supplierClaimUplaod.Error;
ViewBag.SystemCost = supplierClaimUplaod.SystemCost;
ViewBag.Confirmation = supplierClaimUplaod.Error +
supplierClaimUplaod.OrigInv +
supplierClaimUplaod.ST_Key +
supplierClaimUplaod.SupplierClaim +
supplierClaimUplaod.SystemCost;
return View(supplierClaimsData);
}
conn.Close();
}
}
catch (Exception)
{
throw;
}
}
return View(supplierClaimsData);
}
}
}
I managed to pass the controller response to the dialog, I am struggling trigger the loop to go back to the controller and got through all the records. When a user click on Accept Record I want to go back to the controller, and maybe save the record somewhere(sql) and validate the next record and so on, I am basically asking how can I wire up the Jquery button click Accept or Reject to go back to the controller and run additional code based on what button the user selected.
You can do this with an ajax call to your controller action.
$.ajax({
url: "#Url.Action("YourAction", "YourController")",
data: some_parameters
type: "POST",
success: function(response){ },
error: function(jqXHR, textStatus, errorThrown) { }
});
Here for more details

Categories