Search and filter in list ASP.NET MVC - sql

I'm trying to implement search in my list but for some reason, it's not working. I used a jQuery script for searching - please guide me.
Here are my controller and my view:
public ActionResult Details(int S)
{
SLMEntitiesDB dbContext = new SLMEntitiesDB();
var VL = (from U in dbContext.Users
join P in dbContext.Products on U.PID equals P.PID
where P.PID == U.PID
select new UP()
{
UserO = U,
ProductO = P
}).Where(U => U.UserO.LID == S).ToList();
ViewBag.result = VL;
return View(ViewBag.result);
}
View
#model IEnumerable<SLMDemo0.Models.UP>
<input type="text" id="txtsearch" placeholder="Search"/>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.UserO.UserName)
</th>
<th>
#Html.DisplayNameFor(model => model.ProductO.PName)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserO.UserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProductO.PName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.UserO.UID })
</table>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$("txtsearch").on("keyup", function () {
var txtenter = $(this).val();
$("table tr").each(function (results) {
if (results !== 0) {
var id = $(this).find("td:nth-child(2)").text();
if (id.indexOf(txtenter) !== 0 && id.toLowerCase().indexOf(txtenter.toLowerCase()) < 0) {
$(this).hide();
}
else {
$(this).show(); } } }); }); </script>
There's no result from the code, I can view what's in the list but when you type anything in the search nothing is happening.

You have missed the # identifier in $("txtsearch")
Please use it with $("#txtsearch")
<script>
$("#txtsearch").on("keyup", function () {
var txtenter = $(this).val();
$("table tr").each(function (results) {
if (results !== 0) {
var id = $(this).find("td:nth-child(2)").text();
if (id.indexOf(txtenter) !== 0 && id.toLowerCase().indexOf(txtenter.toLowerCase()) < 0) {
$(this).hide();
}
else {
$(this).show(); } } }); }); </script>

Related

Razor Page Cascade Datatables by Dropdown

i have a dropdown list and i want to reload the datatable once i change the dropdown please note that the Checkbox field postback the page as well to update the database below is the cs file and will post the cshtml after
public class IndexModel : PageModel
{
private readonly IpponAcademy.Models.IJAContext _context;
public List<SelectListItem> judokaGroupList { get; set; }
[BindProperty]
public Boolean IsAttend { get; set; }
public IList<tbl_Judoka> tbl_Judoka { get;set; }
public IndexModel(IpponAcademy.Models.IJAContext context)
{
_context = context;
}
public void OnGet(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
if (id == null)
{
id = Guid.Parse("7F299B82-3397-40F2-8105-65AECB1BA2A8"); //Group A
}
tbl_Judoka = _context.tbl_Judokas.Where(c => c.tbl_Judoka_Groups.Any(o => o.Is_Active == true && o.Group_GUID == id)).Include(c => c.tbl_Judoka_Groups.Where(o => o.Is_Active == true && o.Group_GUID == id)).ToList();
}
public void OnGetJudoka(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
if (id == null)
{
id = Guid.Parse("7F299B82-3397-40F2-8105-65AECB1BA2A8"); //Group A
}
tbl_Judoka = _context.tbl_Judokas.Where(c => c.tbl_Judoka_Groups.Any(o => o.Is_Active == true && o.Group_GUID == id)).Include(c => c.tbl_Judoka_Groups.Where(o => o.Is_Active == true && o.Group_GUID == id)).ToList();
}
}
below is the cshtml file, I'd appreciate finding a simple way to do refresh the datatable with the new selected field from the dropdown
#page
#model IpponAcademy.Pages.Attendance.IndexModel
#{
ViewData["Title"] = "Index";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<form method="post">
<div class="form-group">
<label class="control-label">Group</label>
<select id="ddlGroup" class="form-control" asp-items="Model.judokaGroupList"></select>
#*onchange="alert(#Model.judokaGroupList)"*#
</div>
<table id="taskDt" class="table table-striped table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th>
Attended
</th>
<th>
Code
</th>
<th>
Image
</th>
<th>
Judoka
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.tbl_Judoka)
{
var imagePath = #"UploadedFiles/" + item.J_Image;
<tr>
<td>
<input type="hidden" name="J_GUID" id="J_GUID" value="#item.J_GUID" />
<input asp-for="IsAttend" name="IsAttend" id="IsAttend" type="checkbox" onclick="this.form.submit()" />
</td>
<td>
#Html.DisplayFor(modelItem => item.J_Code)
</td>
<td align="center">
<img src="#imagePath" alt="Judoka" width="50" height="50" class="rounded-circle mr-1" onclick="return LoadDiv(this.src);" style="cursor: pointer" />
</td>
<td>
#Html.DisplayFor(modelItem => item.J_Name)
</td>
</tr>
}
</tbody>
</table>
</form>
#section scripts{
<script>
var table;
function LoadData() {
//alert('in');
table = $("#taskDt").DataTable({
paging: true,
responsive: true,
searching: true,
ordering: true,
order: [[1, "asc"]]
});
}
$(document).ready(function () {
LoadData();
})
$("#ddlGroup").change(function () {
alert('DDLGroup');
//table.ajax.url("/Attendance/Index?handler=GET&Id=" + $("#ddlGroup Option:Selected").val()).load();
window.location.href = '/Attendance/Index?handler=Judoka&Id=' + $("#ddlGroup Option:Selected").val();
});
</script>
}
I think using window.location.href has been a simple enough way to refresh the datatable.Just one thing you need to improve,OnGet and OnGetJudoka method are the same,why not using just one method.
Change:
$("#ddlGroup").change(function () {
window.location.href = '/Attendance/Index?handler=Judoka&Id=' + $("#ddlGroup Option:Selected").val();
});
To:
$("#ddlGroup").change(function () {
window.location.href = '/Attendance/Index?Id=' + $("#ddlGroup Option:Selected").val();
});
If you must use another way,you could use form.submit():
Note:Be sure add name="id",otherwise the parameter will not bind to the backend.
<form method="post" asp-page-handler="Judoka">
<div class="form-group">
<label class="control-label">Group</label>
<select id="ddlGroup" class="form-control" name="id" asp-items="Model.judokaGroupList"
onchange="this.form.submit()"></select>
</div>
</form>
Backend code:
Change:
public void OnGetJudoka(Guid? id)
To:
public void OnPostJudoka(Guid? id)
BTW,I also have a suggestion that you'd better maintain the selected value after postback :
public void OnGetJudoka(Guid? id)
{
var GroupList = _context.LK_Groups.ToList();
judokaGroupList = GroupList.Select(a =>
new SelectListItem
{
Value = a.Group_GUID.ToString(),
Text = a.Group_Name
}).OrderBy(t => t.Text).ToList();
//maintain the selected value after post back...
var selectedValue= judokaGroupList.Where(a => a.Value == id.ToString()).FirstOrDefault();
selectedValue.Selected = true;
//...
}

How do i send the data to edit boxes on the same page?

i have the following page generated
when i click the Edit link, the record data must be sent to the input boxes on teh same page (without refreshing the page)
currently i have the controller code and views
controller: ProductCategory
public class ProductCategoryController : Controller
{
//
// GET: /ProductCategory/
TUDBEntities _db = new TUDBEntities();
public ActionResult Index(string Code)
{
var categories = _db.mt_ProductCategories
.Where(pc => Code == "" || Code == null|| pc.CatCode == Code)
.Select(
c => new ProductCategory {
Id = c.Id,
CategoryCode = c.CatCode,
Name = c.CatName,
Url = c.Url
});
if (Request.IsAjaxRequest())
{
return PartialView("_ProductCategoryList", categories);
}
return View(categories);
}
[HttpPost]
public ActionResult Save(ProductCategory userData)
{
try
{
if (ModelState.IsValid)
{
mt_ProductCategories cat = new mt_ProductCategories { CatCode = userData.CategoryCode, CatName = userData.Name };
// TODO: Add insert logic here
_db.mt_ProductCategories.Add(cat);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
var category = _db.mt_ProductCategories
.Where(pc => pc.Id == id)
.Select(pc => new ProductCategory
{ Id=pc.Id, CategoryCode=pc.CatCode,Name=pc.CatName }).ToList();
return RedirectToAction("Index", category);
}
}
Index view
#model IEnumerable<eComm1.Models.ProductCategory>
#using(Ajax.BeginForm("Save", "ProductCategory",
new AjaxOptions {
HttpMethod="POST",
UpdateTargetId="prod-grid",
InsertionMode=InsertionMode.Replace,
OnSuccess="loaddivdata"
}))
{
<fieldset class="form-group">
<label for="Code">Category Code</label>
<input type="text" class="form-control focus" id="Code" name="CategoryCode" placeholder="Product category code" >
</fieldset>
<fieldset class="form-group">
<label for="ProdName">Product Name</label>
<input type="text" class="form-control" id="ProdName" name="Name" placeholder="Product Name">
</fieldset>
<button type="Submit" class="btn btn-primary">Save</button>
}
<hr />
<div id="prod-grid">
#Html.Partial("_ProductCategoryList", #Model)
</div>
<script type="text/javascript">
$(function () {
$('.focus :input').focus();
});
function loaddivdata() {
$('#prod-grid').html();
$('#Code, #ProdName').val('');
};
// $('#prod-grid').load(function () {
// $.ajax({
// url:'ProductCategoryController/Index',
// method:'GET',
// type:'application/html',
// success: function () { alert('called');}
// });
// });
//});
</script>
Partial View: _ProductCategoryList
#model IEnumerable<eComm1.Models.ProductCategory>
<div class="panel panel-default">
#if (Model.Count() == 0) { <div class="panel-heading">Product Categories - <span style='color:red;font-weight:bold' >0 RESULTS FOUND</span></div>
}else{
<!-- Default panel contents -->
<div class="panel-heading">Product Categories</div>
}
<!-- Table -->
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CategoryCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Url)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CategoryCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Url)
</td>
<td>
#*#Html.beActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })*#
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id=item.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", UpdateTargetId="", OnSuccess="loadformdata"})
</td>
</tr>
}
</table>
</div>
How do i modify my code to send data those input control and in my code how do i create hidden field for Id value so it can be send to the Edit(collection, int id) action to update the record?
for Stephen Muecke, i have added my jquery files through the bundles
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/ecomm").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-2.1.4.min.js",
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap.min.js",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"
));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.min.css",
"~/Content/bootstrap.css",
"~/Content/style.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
In the partial view
#Ajax.ActionLink("Edit", "Edit", "ProductCategory", new { id = item.Id }, new AjaxOptions { HttpMethod = "GET", OnSuccess = "loadformdata" }) |
#Ajax.ActionLink("Delete", "Delete", "ProductCategory", new { id=item.Id}, new AjaxOptions{ HttpMethod="POST", OnSuccess="loadformdata"})
in the index view the following js function:
function loadformdata() {
var cells = $(this).closest('tr').children('td');
alert(cells.eq(0).text());
//$('#Code').val(cells.eq(0).text());
//$('#ProdName').val(cells.eq(1).text());
}
To: Stephen Muecke:
i have removed above loadformdata() and put everything as you said. this youtube video shows the problem that still does not call that click event
To: Steven Meucke:
there's still no luck, for ease i have added a alert() in the function and the alert() won't show. Here is the video
Give you 'Edit' link a class name (say) class="edit" and handle its .click() event to update the form controls
$('.edit').click(function() {
var cells = $(this).closest('tr').children('td');
$('#Code').val(cells.eq(0).text());
$('#ProdName').val(cells.eq(1).text());
return false; // cancel the default redirect
});
Side note: You could just replace the ActionLink() code with Edit and the return false; line is not necessary.
write script for ajax call:
$('#edit').click(function () {
// var data = {here you will pass item.id }
$.ajax({
url:'ProductCategoryController/Edit',
data: {id : data}
method:'GET',
success: function (data) {
//clear html page here
//reload html page by passing 'data' passes in function
//e.g. suppose html page id is 'xyz' then $("#xyz").html(data)
}
});
});

Data inserting using jquery, AJAX in ASP.NET MVC4?

I am trying to insert data to the database. For that I am using ajax and jquery, but the values from textbox are coming null and inserting the same in database. Here is the code of html markup and jQuery button click event handling:
#using (#Html.BeginForm("VewResult", "States" ))
{
<table >
<tr>
<td>State ID</td> <td > #Html.TextAreaFor(m => m.StateID, new { ID = "txtStateid", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>District ID</td> <td> #Html.TextAreaFor(m => m.DistrictID, new { ID = "txtdistrictid", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>State Name</td> <td> #Html.TextAreaFor(m => m.StateName, new { ID = "txtStatendame", style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td colspan="2"> <input type="Submit" id="btnAjax" name="btnAjax" value="Insert It"></td>
</tr>
</table>
<div id="result"></div>
}
#section Scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#btnAjax').click(function () {
alert($('#txtStateid').val());
var stateid = $('#txtStateid').val();
var districtid = $('#txtdistrictid').val();
var statename = $('#txtStatendame').val();
if (stateid != "" && districtid != "" & statename != "") {
$.ajax({
url: '/States/VewResult',
contentType: 'application/html; charset=utf-8',
data: { stid: stateid, districid: districtid, stname: statename },
type: 'POST',
dataType: 'html',
success(function (result) {
$('#result').html('Inserted Successfully');
})
});
error(function (xhr, status) {
alert(status);
})
}
else {
alert('Enter Stateid,districtid,statename');
}
});
});
</script>
}
Please try below code.
<table >
<tr>
<td>State ID</td> <td > #Html.TextAreaFor(m => m.StateID, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>District ID</td> <td> #Html.TextAreaFor(m => m.DistrictID, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td>State Name</td> <td> #Html.TextAreaFor(m => m.StateName, new { style = "width:150px;height:20px" }) </td>
</tr>
<tr>
<td colspan="2"> <input type="Submit" id="btnAjax" name="btnAjax" value="Insert It"></td>
</tr>
</table>
<div id="result"></div>
#section Scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#btnAjax').click(function () {
alert($('#txtStateid').val());
var stateid = $('#StateID').val();
var districtid = $('#DistrictID').val();
var statename = $('#StateName').val();
if (stateid != "" && districtid != "" & statename != "") {
$.ajax({
url: '/States/VewResult',
data: { stid: stateid, districid: districtid, stname: statename },
type: 'POST',
dataType: 'html',
success(function (result) {
$('#result').html('Inserted Successfully');
})
});
error(function (xhr, status) {
alert(status);
})
}
else {
alert('Enter Stateid,districtid,statename');
}
});
});
</script>
There is no need of form tag is required if you are calling as ajax. Or instead of jQuery ajax you can use Ajax.Beginform() . For this please refer
And your action will be
Public ActionResult VewResult(string stid,string districid,string stname)
{
//Your body
return;
}
Your are sending the data in HTML format to the Controller Action. Instead pass it as JSON. This link would be helpful to implement it.

return correct data to mvc View

Im trying to populate data in a view from an sql db. Im selecting all recipes from a specific counry...O.k...I also want to display the country name at the top of the view but im having problems returning the result to the view. Any ideas would be greatly appreciated...
Heres my code
#model IEnumerable<FoodB.recipeTbl>
<h2>************where i want to put the country title***************88</h2>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.recipe_title)
</th>
<th>
#Html.DisplayNameFor(model => model.ingredients)
</th>
<th>
#Html.DisplayNameFor(model => model.country_id)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.recipe_title)
</td>
<td>
#Html.DisplayFor(modelItem => item.ingredients)
</td>
<td>
#Html.DisplayFor(modelItem => item.country_id)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Details", "Details", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
</table>
Here's my controller
public ActionResult Index(int id)
{
//select all recipes for country
var query = db.recipeTbls.Where(c => c.country_id == id);
//get country from country table*******how to return this***********
var ctry = db.countryTbls.Where(country => country.id == id);
return View(query);
}
Use SingleOrDefault instead of Where since you are looking for one entry only
public ActionResult Index(int id)
{
//select all recipes for country
var query = db.recipeTbls.SingleOrDefault(c => c.country_id == id);
//get country from country table*******how to return this***********
var ctry = db.countryTbls.SingleOrDefault(c => c.id == id);
ViewBag.Country = ctry;
return View(query);
}
View
<h1>ViewBag.Country </h1>
viewbag is a field that is dynamic. you can set it to whatever type you want. So on your controller
ViewBag.Country = ctry;
then in your view
<label>#ViewBag.Country</label>
You can use the ViewBag.
The controller
public ActionResult Index(int id)
{
//select all recipes for country
var query = db.recipeTbls.Where(c => c.country_id == id);
//get country from country table*******how to return this***********
var ctry = db.countryTbls.Where(country => country.id == id);
ViewBag.country = ctry.ToString();
return View(query);
}
The view
#model IEnumerable<FoodB.recipeTbl>
<h2>ViewBag.country</h2>
Hope it worked.

Paypal IPN and PDT in MVC 4.0

I beginner of MVC and i am trying to paypal payment process using the following link
http://www.arunrana.net/2012/01/paypal-integration-in-mvc3-and-razor.html
Please guide me
How to implement Paypal IPN and PDT
and how to get success and Transaction id from Paypal that i want to save in database
Thanks in Advance
"
public class CheckoutController : Controller
{
CartContext _CartCotext = new CartContext();
CartItemContext _CartItemContext = new CartItemContext();
Tbl_OrderContext _OrderContext = new Tbl_OrderContext();
OrderDetailContext _OrderDetailContext = new OrderDetailContext();
ProductContext _ProductContext = new ProductContext();
const string PromoCode = "FREE";
[HttpPost]
public ActionResult AddressAndPayment(CheckoutViewModel values)
{
var cart = ShoppingCart.GetCart(this.HttpContext);
var _CartItems = Session["CartItems"];
var list = (List<Cart>)Session["CartItems"];
values.CartItems = list;
var order = new CheckoutViewModel();
order.CartItems = list;
TryUpdateModel(order);
{
try
{
if (order.Tbl_Order == null)
{
return View(order);
}
else
{
order.Tbl_Order.Username = User.Identity.Name;
order.Tbl_Order.OrderDate = DateTime.Now;
order.Tbl_Order.CartTotal = order.CartTotal;
Session["carttotal"] = order.CartTotal;
order.Tbl_Order.Status = "Pending";
//Save Order
_OrderContext.OrderEntries.Add(order.Tbl_Order);
_OrderContext.SaveChanges();
//Process the order
string username = User.Identity.Name;
ShoppingCart obj = new ShoppingCart();
int i = obj.CreateOrder(order.Tbl_Order, order.CartItems, username);
//return RedirectToAction("Complete",
// new { id = order.Tbl_Order.OrderId });
return RedirectToAction("PosttoPaypalShow");
}
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
}
[HttpGet]
public ActionResult PosttoPaypalShow()
{
SportsStore.Models.Paypal payPal = new Paypal();
payPal.cmd = "_xclick";
payPal.business = ConfigurationManager.AppSettings["BusinessAccount"];
bool useSendBox = Convert.ToBoolean(ConfigurationManager.AppSettings["useSendbox"]);
if (useSendBox)
{
ViewBag.actionURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
}
else
{
ViewBag.actionURL = "https://www.paypal.com/cgi-bin/webscr";
}
payPal.cancel_return = System.Configuration.ConfigurationManager.AppSettings["CancelUrl"];
payPal.#return = ConfigurationManager.AppSettings["ReturnURL"];
payPal.notify_url = ConfigurationManager.AppSettings["NotifyURL"];
payPal.currency_code = ConfigurationManager.AppSettings["currencycode"];
//payPal.item_Name = ProductName;
payPal.item_Name = "test1";
payPal.Descriptions = "tes2";
payPal.amount = String.Format("{0:0.##}", Session["carttotal"]); //Convert.ToString(Session["carttotal"].ToString("0.00"));
return View(payPal);
}
public ActionResult PaypalAddressAndPayment()
{
Tbl_Order order = new Tbl_Order();
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up the ViewModel
var viewModel = new CheckoutViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal(),
Tbl_Order = order
};
Session["CartItems"] = viewModel.CartItems;
return View(viewModel);
//return View(order);
}
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
StringBuilder sb = new StringBuilder();
sb.Append(strRequest);
foreach (string key in formVals.Keys)
{
sb.AppendFormat("&{0}={1}", key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;
//for proxy
//WebProxy proxy = new WebProxy(new Uri("http://urlort#");
//req.Proxy = proxy;
//Send the request to PayPal and get the response
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
return response;
}
public ActionResult IPN()
{
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
if (response == "VERIFIED")
{
string transactionID = Request["txn_id"];
string sAmountPaid = Request["mc_gross"];
string orderID = Request["custom"];
string pay_Status = Request["payment_status"];
//_logger.Info("IPN Verified for order " + orderID);
//validate the order
Decimal amountPaid = 0;
Decimal.TryParse(sAmountPaid, out amountPaid);
//Order order = _orderService.GetOrder(new Guid(orderID));
Tbl_Order order = null;
//check the amount paid
if (AmountPaidIsValid(order, amountPaid))
{
Tbl_Order add = new Tbl_Order();
add.Username = User.Identity.Name;
//add.FirstName = Request["first_name"];
//add.LastName = Request["last_name"];
//add.Email = Request["payer_email"];
//add.Address = Request["address_street"];
//add.City = Request["address_city"];
//add.State = Request["address_state"];
//add.Country = Request["address_country"];
//add.PostalCode = Request["address_zip"];
add.TransactionId = transactionID;
add.Status = pay_Status;
add.CartTotal = Convert.ToDecimal(sAmountPaid);
//process it
try
{
_OrderContext.OrderEntries.Add(add);
_OrderContext.SaveChanges();
//_pipeline.AcceptPalPayment(order, transactionID, amountPaid);
//_logger.Info("IPN Order successfully transacted: " + orderID);
//return RedirectToAction("Receipt", "Order", new { id = order.ID });
}
catch
{
//HandleProcessingError(order, x);
return View();
}
}
else
{
//let fail - this is the IPN so there is no viewer
}
}
return View();
}
bool AmountPaidIsValid(Tbl_Order order, decimal amountPaid)
{
//pull the order
bool result = true;
if (order != null)
{
if (order.CartTotal > amountPaid)
{
//_logger.Warn("Invalid order amount to PDT/IPN: " + order.ID + "; Actual: " + amountPaid.ToString("C") + "; Should be: " + order.Total.ToString("C") + "user IP is " + Request.UserHostAddress);
result = false;
}
}
else
{
//_logger.Warn("Invalid order ID passed to PDT/IPN; user IP is " + Request.UserHostAddress);
}
return result;
}
}
public class Address
{
public string FirstName { set; get; }
public string LastName { set; get; }
public string Email { set; get; }
public string Street1 { set; get; }
public string City { set; get; }
public string StateOrProvince { set; get; }
public string Country { set; get; }
public string Zip { set; get; }
}"
and
following the web.config file configuration
<add key="BusinessAccount" value="anilcs_1361585097_biz#gmail.com" />
<add key="useSendbox" value="true" />
<add key="currencycode" value="USD" />
<add key="ReturnURL" value="http://localhost:49424/Checkout/IPN" />
<add key="CancelUrl" value="http://localhost:49424/SportsStore/CancelFromPaypal" />
<add key="NotifyURL" value="http://localhost:49424/SportsStore/NotifyFromPaypal" />
<!--test MarchnatAccountId-->
<add key =" MerchantAccountID" value="RCERFF5KTC784"/>
This is my cart
#model SportsStore.Models.Paypal
#{
Layout = null;
}
<html>
<head>
<title>Index</title>
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
</html>
<form id="frm" action="#ViewBag.Actionurl">
#Html.HiddenFor(Model => Model.cmd)
#Html.HiddenFor(Model => Model.business)
#Html.HiddenFor(Model => Model.no_shipping)
#Html.HiddenFor(Model => Model.#return)
#Html.HiddenFor(Model => Model.cancel_return)
#Html.HiddenFor(Model => Model.notify_url)
#Html.HiddenFor(Model => Model.currency_code)
#Html.HiddenFor(Model => Model.item_Name)
#Html.HiddenFor(Model => Model.amount)
</form>
<p style="text-align: center">
<h4>
Redirecting to Paypal</h4>
</p>
<script type="text/javascript" language="javascript">
$(this.document).ready(function () {
var frm = $("form");
frm.submit();
});
</script>
after that i will filled up the shipping details and my page redirect to paypal
{
#model SportsStore.Models.CheckoutViewModel
#{
ViewBag.Title = "Address And Payment";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("AddressAndPayment", "Checkout"))
{
<table>
<thead>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.OrderId, "OrderId")
</th>
<td>
#Html.TextBoxFor(m => m.Tbl_Order.OrderId, new { disabled = "disabled", #readonly = "readonly" })
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.OrderDate, "OrderDate")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.OrderDate, "OrderDate")
#Html.EditorFor(m => m.CartItems, "CartItems")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.FirstName, "First Name")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.FirstName, "First Name")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.LastName, "Last Name")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.LastName, "Last Name")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.Address, "Address")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.Address, "Address")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.City, "City")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.City, "City")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.State, "State")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.State, "State")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.PostalCode, "PostalCode")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.PostalCode, "PostalCode")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.Country, "Country")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.Country, "Country")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.Phone, "Phone")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.Phone, "Phone")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.Tbl_Order.Email, "Email")
</th>
<td>
#Html.EditorFor(m => m.Tbl_Order.Email, "Email")
</td>
</tr>
<tr>
<th>
#Html.LabelFor(m => m.CartTotal, "Total")
</th>
<td>
#* #Html.EditorFor(m => m.CartTotal, "Total" ) *# #* #Html.TextBoxFor(m => m.CartTotal, new { disabled = "disabled", #readonly = "readonly" })*#
#* #Html.DisplayTextFor(m => m.CartTotal)*#
#Html.TextBoxFor(m => m.CartTotal, new { #readonly = "readonly" })
</td>
</tr>
<tr>
<td>
</td>
Continoue with paypal
<td>
</td>
</tr>
<tr>
<td>
#* #Html.ActionLink("Sure to payment", "PosttoPaypalShow", "Checkout")*#
<input type="submit" value="Submit" />
</td>
</tr>
</thead>
</table>
}
1 Question - this is proper way which i have done ?
2 Question - how to return custom value from Paypal
3 and also see the web.config file after the payment should i called the PIN ?
Please guide me ...... and how to do payment process
I was looking for information on this recently as well. There is sample code on the paypal site, but I find it quite terse and it is hard to put it into context in your application. The best that I could find is the video and sample by Rob Conery.
First, look at the video. It is called "ASP.NET MVC Storefront Part 1: Architectural Discussion and Overview". Currently it can be found here. Skip ahead to 15:21 to get to the paypal part.
Then download the source code. You are looking for 'ASP.NET MVC Storefront sample code which can currently be found here.
Once you have extracted the code, search for IPN() for IPN method and PDT() for PDT method.