Angular Application code not checking username and Password from wcf service - c#

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.

Related

Ajax & ASP.NET MVC : get data by ID without using Entity Framework

I am trying to get data in my DataTable by ID, the data row coming from SQL Server to my controller but I am confused: how to pass this data to my DataTable in view?
I am using this code - my model:
public class EmployeesModel
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Position { get; set; }
public string Office { get; set; }
[Required(ErrorMessage ="Please enter date")]
public DateTime HiringDate { get; set; }
public int Salary { get; set; }
}
My controller
public JsonResult GetEmpByID(int id)
{
List<EmployeesModel> employeeList = new List<EmployeesModel>();
string CS = ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_GetEmpByID", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpID", SqlDbType.NVarChar).Value = id; //Added Parameter
conn.Open();
// Get
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EmployeesModel employee = new EmployeesModel();
employee.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
employee.Name = reader["Name"].ToString();
employee.Gender = reader["Gender"].ToString();
employee.Age = Convert.ToInt32(reader["Age"]);
employee.Position = reader["Position"].ToString();
employee.Office = reader["Office"].ToString();
employee.HiringDate = Convert.ToDateTime(reader["HiringDate"]);
employee.Salary = Convert.ToInt32(reader["Salary"]);
employeeList.Add(employee);
}
}
//return View(employeeList); Commented out
//return RedirectToAction("GetEmpByID"); Commented out
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
}
My view
#model IEnumerable<SQLWithoutEF.EmployeesModel>
<input type="text" id="tablename" /> //Here I enter Employee ID and below is button
<asp:Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#tablename').val())">Get Data By ID</asp:Button>
#*Data Table ==============*#
<table class="table table-bordered table-responsive table-hover" id="MyTable">
<thead>
<tr>
<th style="display:none">#Html.DisplayNameFor(m => m.EmployeeId)</th>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.Gender)</th>
<th>#Html.DisplayNameFor(m => m.Age)</th>
<th>#Html.DisplayNameFor(m => m.Position)</th>
<th>#Html.DisplayNameFor(m => m.Office)</th>
<th>#Html.DisplayNameFor(m => m.HiringDate)</th>
<th>#Html.DisplayNameFor(m => m.Salary)</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var employee1 in Model)
{
<tr>
<td style="display:none">#employee1.EmployeeId</td>
<td>#employee1.Name</td>
<td>#employee1.Gender</td>
<td>#employee1.Age</td>
<td>#employee1.Position</td>
<td>#employee1.Office</td>
<td>
#if (employee1.HiringDate != null)
{
#employee1.HiringDate
}
</td>
<td>#employee1.Salary</td>
<td>
<asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> |
<asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button>
</td>
</tr>
}
</tbody>
</table>
My jQuery / Ajax - here I need help:
function GetByName(id) {
if (confirm("Are You Sure to Get " + id + " " + " ?")) {
$('#MyTable tbody tr').remove();
$.ajax({
type: "GET",
url: '/Home/GetEmpByID?id=' + id,
//data: JSON.stringify({ id: id }),
//contentType: application/json, charset: utf-8,
processData: false,
dataType: 'json',
bprocessing: true,
success: function (data) { // Till here data coming but it's not working further
var items = '';
$.each(data, function (item) {
debugger;
var rows = '';
for (var i = 0; i < item.length[0]; i++) {
rows = "<tr><td>" + data + "</td>"
+ '<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button></td>'
"</tr>";
$('#MyTable tbody').append(rows);
}
})
},
}).catch(function (xhr, status, error) {
var errorMeassage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMeassage);
})
};
};
Here is the screenshot what output I am getting
enter image description here
Kindly suggest how I can send data from my controller to my DataTable using Ajax?
Thanks
From the controller API action,
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
It will return the response with body as an object with data property which contains the array, instead of the response is the array.
The response body would be as:
{
data: [/* Employee List */]
}
In JavaScript part, to take the employee array
var items = data.data;
The implementation in success callback should be:
var items = data.data;
$.each(items, function (index, item) {
debugger;
var rows = '';
rows = `<tr>
<td style="display:none">${item.EmployeeId}</td>
<td>${item.Name}</td>
<td>${item.Gender}</td>
<td>${item.Age}</td>
<td>${item.Position}</td>
<td>${item.Office}</td>
<td>${item.HiringDate}
</td>
<td>${item.Salary}</td>
<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="${item.Name}" id="deletebtn" onclick="deleteF(${item.EmployeeId}">DeleteEmp</asp:button></td>
</tr>`;
$('#MyTable tbody').append(rows);
})
Note: You may use the string interpolation / template literal which makes it easier to build the template string.
Demo

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)

why is file.PostedFile is always null

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.

Simple Search / Filter Function to Database (ASP.NET MVC) (SQL Server 2014)

I would like to add a simple search function in my simple database.
I have completed an add, edit & delete function. I have difficulty dealing with the search function.
Currently I have a search box and I have thought of the proper SQL query to execute in the database so I can get a simple result.
I have difficulty in passing the textbox field to the controller so that it can be used as search query in the SQL Database, and then bringing it back to the view for the search results.
I am an ASP.NET MVC beginner. Please help. Thank you very much!
Here is my work so far:
View
#model IEnumerable<SampleReg.Models.Course>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm("Search", "Course", FormMethod.Post))
{
<input type="text" name="txtsearch" value=" " />
<input type="submit" name="btnsubmit" value="submit" />
}
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.crs_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.crs_Course)
</th>
<th>
#Html.DisplayNameFor(model => model.crs_Major)
</th>
<th>
#Html.DisplayNameFor(model => model.crs_Spec)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.crs_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.crs_Course)
</td>
<td>
#Html.DisplayFor(modelItem => item.crs_Major)
</td>
<td>
#Html.DisplayFor(modelItem => item.crs_Spec)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.crs_ID }) |
#Html.ActionLink("Details", "Details", new { id = item.crs_ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.crs_ID })
</td>
</tr>
}
</table>
Controller
public ActionResult Index()
{
return View(GetAllCourse(""));
}
[HttpPost, ActionName("Search")]
[ValidateAntiForgeryToken]
public ActionResult Search(string GetAllCourse) {
string search = Request.Form["txtsearch"].ToString();
//GetAllCourse("search");
return View();
}
#region PRIVATE FUNCTIONS
private List<Course> GetAllCourse(string search)
{
//DECLARATION AND INIT
SqlConnection oCon = null;
SqlCommand oCmd = null;
SqlDataReader oDr = null;
List<Course> oList = null;
string SqlCon = #"Data Source=IT-MARICOR\LOCAL;Initial Catalog=INTERN;User ID=sa;Password=aaa";
try
{
//SET CONNECTION
oCon = new SqlConnection();
oCon.ConnectionString = SqlCon;
if (oCon.State == System.Data.ConnectionState.Closed)
{
oCon.Open();
}
//SET COMMAND
oCmd = new SqlCommand();
oCmd.Connection = oCon;
oCmd.CommandType = System.Data.CommandType.Text;
oCmd.CommandText = "SELECT * FROM Course " + (search == "" ? "" : " WHERE crs_Course LIKE '% " + search + "%'");
oDr = oCmd.ExecuteReader();
if (oDr.HasRows)
{
oList = new List<Course>();
while (oDr.Read())
{
Course oCourse = new Course();
oCourse.crs_ID = Convert.ToInt32(oDr["crs_ID"].ToString());
oCourse.crs_Course = oDr["crs_Course"].ToString();
oCourse.crs_Major = oDr["crs_Major"].ToString();
oCourse.crs_Spec = oDr["crs_Specialization"].ToString();
oList.Add(oCourse);
}
return oList;
}
return null;
}
catch (Exception ex)
{
throw ex;
}
finally
{
//CLEAN UP RESOURCES
oCon.Close();
oCon = null;
}
}
#endregion
Here is what it looks like:
OR you can take help of jquery ajax method.
give one id to text box.
var Url = "/Course/Search",
var textvalue= $('#textboxid').val(),
$.ajax({
url: Url ,
data: { GetAllCourse: textvalue},
type: "GET",
url: Path,
success: function (result) {
}
});

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