Asp .net MVC...HttpPostedFileBase uploadImage is not always null - asp.net-mvc-4

I want upload an Image but it always gets null. I'm using HttpPostedFileBase.
This is my COntroller
public ActionResult EmployeeDetail(EmployeeModel employee, HttpPostedFileBase UploadImage)//this UploadImage Object is always null
{
EmployeeModel employeeModel = new EmployeeModel();
if (string.IsNullOrEmpty(employeeModel.Name))
{
ModelState.AddModelError("Name", "Name is Required");
}
employeeModel.Name = employee.Name;
if (string.IsNullOrEmpty(employeeModel.DOJ))
{
ModelState.AddModelError("DOJ", "DOJ is Requird");
}
employeeModel.DOJ = employee.DOJ;
if (string.IsNullOrEmpty(employeeModel.DOB))
{
ModelState.AddModelError("DOB", "DOB is Required");
}
employeeModel.DOB = employee.DOB;
if (string.IsNullOrEmpty(employeeModel.Designation))
{
ModelState.AddModelError("Designation", "Designation is required");
}
employeeModel.Designation = employee.Designation;
string ImageName = Path.GetFileName(UploadImage.FileName);
string Physicalpath = Server.MapPath("~/images/" + ImageName);
UploadImage.SaveAs(Physicalpath);
employee.UploadImage = Physicalpath;
//string ImageName = Path.GetFileName(image.FileName);
//string physicalPath = Server.MapPath("~/images/" + ImageName);
//image.SaveAs(physicalPath);
// ModelState.AddModelError("UploadImage", "upload is required");
//employee.UploadImage = physicalPath;
EmployeeBusinessLayer employeeBL = new EmployeeBusinessLayer();
employeeBL.InsertDataRegistration(employeeModel);
return RedirectToAction("Index");
}
This is my View
#using (Html.BeginForm("EmployeeDetail", "Home", FormMethod.Post, new { enctype = "multipart/form-data", #data_ajax = "false" })) //i have used all the codes which could be need to make it work...still not working
{
<div class="MainDiv">
<table class="Table">
<tr class="Row">
<td class="Column1"> Name</td>
<td class="Column2">#Html.TextBoxFor(model => model.Name) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DOJ </td>
<td class="Column2">#Html.TextBoxFor(model => model.DOJ, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name) </td>
</tr>
<tr class="Row">
<td class="Column1">DOB</td>
<td class="Column2">#Html.TextBoxFor(model => model.DOB, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DESIGNATION</td>
<td class="Column2">#Html.TextBoxFor(model => model.Designation) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">UPlOAD </td>
<td class="Column2">#Html.TextBoxFor(model => model.UploadImage, new { #type = "File" })
</td>
</tr>
<tr class="Row">
<td colspan="2">
<input type="submit" class="button" name="submit" value="Submit">
<input type="reset" class="button1" value="Clear" name="Clear">
</td>
</tr>
</table>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/jquery-1.8.3.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/ui/minified/jquery-ui.custom.min.js"></script>
<script type="text/javascript">
$(function () {
// This will make every element with the class "date-picker" into a DatePicker element
$('.datepicker').datepicker();
})
</script>
</div>
}
this is my Model
public Model
{
public int EmployeeId { get; set; }
[Required(ErrorMessage = "this is required")]
public string Name { get; set; }
[Required (ErrorMessage = "This is required")]
public string DOJ { get; set; }
[Required(ErrorMessage ="This is required")]
public string DOB { get; set; }
[Required(ErrorMessage ="This is required")]
public string Designation { get; set; }
[Required(ErrorMessage = "This is required")]
public string UploadImage { get; set; }
public HttpPostedFileBase MyFile { get; set; }
}

I don't see anywhere you are passing any parameter to EmployeeDetail(). Are you able to get data for your EmployeeModel? If yes, then that at least confirm that your view able to call the EmployeeDetail() action.
Next, you need to make sure you are passing proper parameter to your EmployeeDetail(). One of the way I could think of is to use ajax. So you can create an ajax call when submit button is clicked, and pass all your data and the uploaded file input in the ajax method.
This is an example of using ajax call with JQuery syntax to pass data to the action
var inputFiles = $('inpFile').val();
var actMethod = "#Url.Action("EmployeeDetail", "Index")"
var postData = {
"Name": $('inpName').val(),
"DOJ": $('inpDOJ').val(),
...
"UploadImage": inputFiles
}
$.ajax()
{
url: actMethod ,
data: postData,
type: "POST",
success: function (data) {
alert("Insert Successful!");
}
}

Related

Get data from Ajax in ASP.NET Core not working?

I'm new at ASP.NET Core, and this is how I get data from Ajax.
I have a View Model like this
public class RequestSearchDefaultModel
{
public string FromToDate { get; set; }
public int Status { get; set; }
public List<SelectListItem> StatusType { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public IEnumerable<RequestViewModel> requestViewModel { get; set; }
}
When I search the form, I use Ajax to get the data
function OpenSearch() {
var stt = $('#StatusDropDown').val();
var daterange = $('#daterange').val();
var url = "#Url.Action("Search","RequestApproval")";
var model = { FromToDate: daterange, Status: stt };
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
}).done(function (res) {
console.log("here");
$('#myTable').html(res);
})
}
This is controller
[HttpPost]
public async Task<IActionResult> Search([FromBody] RequestSearchDefaultModel m)
{
m.FromDate = DateTime.Parse(m.FromToDate.Substring(0, 10)).Add(new TimeSpan(00, 0, 0));
m.ToDate = DateTime.Parse(m.FromToDate.Substring(14)).Add(new TimeSpan(23, 59, 59));
var request = _headerService.Search();
m.requestViewModel = _mapper.Map<IEnumerable<RequestViewModel>>(request);
return PartialView("_RequestBody", m);
}
This is the view
<div class="card-body">
<div class="table-responsive" id="myTable">
#Html.Partial("_RequestBody")
</div>
</div>
And this is the partial view
#model RequestSearchDefaultModel
<table class="table table-striped">
<thead>
<tr>
<th>Seq.</th>
<th>Title</th>
<th>Status</th>
<th>Draft Date</th>
<th>Final Approval Date</th>
</tr>
</thead>
<tbody id="RequestBody">
#if (Model.requestViewModel == null)
{
}
else
{
foreach (var item in Model.requestViewModel)
{
<tr>
<td>#item.ID</td>
<td>#item.DocumentNo</td>
<td>
<a asp-action="Edit" asp-route-id="#item.ID">#item.Title</a>
</td>
<td>#item.DraftDate</td>
</tr>
}
}
</tbody>
</table>
But I can't get the data, I don't know where I wrong, so please help. Thanks in advance.

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;
//...
}

partial view not displaying on main view post back

In the main view I am calling a partial view. It work fine for normal usage. On the postback the partial view controller bit is never triggered and the partial view does not displayed. What options are available to make sure that the partial view is rendered even when a postback is triggered.
Model:
public class ReportSummary
{
public int PayrollNumber { get; set; }
public string Name { get; set; }
public string ConflictInterest { get; set; }
public string SummaryConflictInterest { get; set; }
public string FinancialInterest { get; set; }
public string SummaryFinancialInterest { get; set; }
public string GiftInterest { get; set; }
public string SummaryGiftInterest { get; set; }
public string Combined { get; set; }
public string SummaryCombined { get; set; }
}
Controller:
Main:
public ActionResult CoiReporting()
{
...
var model = new ReportParamters();
model.Year = DateTime.Today.Year-1;
model.SelectedTab = "0";
...
return View(model);
}
[HttpPost]
[ActionName("CoiReporting")]
public ActionResult CoiReportingConfrim(string ViewReport, ReportParamters model )
{
...
switch (model.SelectedTab)
{
...
}
return View(model);
}
Partial:
public ActionResult _ReportCriteria(int Year=0, int ReportType=0, int Person=0, int Group=0, int Division=0, int Department=0, int Section=0, string SelectedTab="X")
{
...
var model = new ReportParamters();
model.Year = Year;
model.ReportType = ReportType;
model.Person = Person;
model.Group = Group;
model.Division = Division;
model.Department = Department;
model.Section = Section;
model.SelectedTab = SelectedTab;
return PartialView(model);
}
Views:
Main
#model ConflictOfInterest.Models.ReportParamters
#using (Html.BeginForm("CoiReporting", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.SelectedTab)
#Html.HiddenFor(model => model.Year)
<div id="tabs">
<ul>
<li>Summary</li>
<li>Statistics</li>
<li>Statistics with Person Detail</li>
</ul>
<div id="tabs-1">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</div>
<input type="submit" name="ViewReport" id="ViewReport" value="View Report" class="SaveForm" />
<script type="text/javascript">
$(function () {
var sPath = "";
var sParam = "";
$("#tabs").tabs({
activate: function (event, ui) {
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
....
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.newPanel.load(sPath + sParam);
},
active: $("#SelectedTab").val()
});
});
$('#tabs').click('tabsselect', function (event, ui) {
var selectedTab = $("#tabs").tabs("option", "active");
$("#SelectedTab").val(selectedTab);
});
</script>
}
Partial:
#model ConflictOfInterest.Models.ReportParamters
#{
if (Model.SelectedTab != "0")
{
<table border="0" cellpadding="0" cellspacing="0">
#{
if (Model.SelectedTab == "1")
{
<tr>
<td style="font-weight:bolder">#Html.Label("Year", "Year:")</td>
<td>#Html.DropDownListFor(model => model.Year, Enumerable.Empty<SelectListItem>(), (DateTime.Today.Year - 1).ToString(), new { #style = "width:200px;" })
</td>
<td style="font-weight:bolder">#Html.Label("ReportType", "Report Type:")</td>
<td>#Html.DropDownListFor(model => model.ReportType, new SelectList(ViewBag.ReportType, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">
#Html.Label("Person", "Person:")
#Html.Label("Group", "Group:")
</td>
<td>
#Html.DropDownListFor(model => model.Group, new SelectList(ViewBag.GroupList, "value", "Text"), new { #style = "width:200px;" })
#Html.DropDownListFor(model => model.Person, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })<br />
#Html.TextBox("sPerson")
<input type="button" id="bPerson" value="Search" />
</td>
</tr>
}
/*else
{
<tr>
<td colspan="6"></td>
</tr>
}*/
}
<tr>
<td style="font-weight:bolder">#Html.Label("Division", "Division:")</td>
<td>#Html.DropDownListFor(model => model.Division, new SelectList(ViewBag.Division, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Department", "Department:")</td>
<td>#Html.DropDownListFor(model => model.Department, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Section", "Section:")</td>
<td>#Html.DropDownListFor(model => model.Section, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
</tr>
<tr>
<td colspan="6"></td>
</tr>
</table>
}
else
{
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
}
}
The activate event of the jquery tab is triggered when a tab is activated(selected).
To ensure that the the same action is taking place on post back you need to use the create event as well.
Take note of the difference in the load at the end
create: function (event, ui) {
//event.preventDefault();
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
//console.log("Start Url: " + sUrl);
sPath = sUrl.substring(0, sUrl.lastIndexOf("?") + 1);
//console.log("Path: "+sPath);
//console.log("Parameters:"+sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length));
sParam = sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length)
var aParam = sParam.split("&");
for (var i = 0; i < aParam.length; i++) {
var aParama = aParam[i].split("=");
switch (i) {
case 7:
aParama[1] = selectedTab;
break;
}
aParam[i] = aParama.join("=");
}
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.panel.load(sPath + sParam);
},

CS0234: type or namespace name 'StudentViewModel.' does not exist in the namespace 'ContosoUniversity.ViewModels'

Error : CS0234: The type or namespace name 'StudentViewModel' does not exist in the namespace 'ContosoUniversity.ViewModels' (are you missing an assembly reference?)
https://www.dropbox.com/s/vqusln7le5fklxg/%D0%91%D0%B5%D0%B7%D1%8B%D0%BC%D1%8F%D0%BD%D0%BD%D1%8B%D0%B9.jpg?dl=0
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var students = from s in studentService.GetAll()
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
|| s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default:
students = students.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(students.ToPagedList(pageNumber, pageSize));
}
My Class
using ContosoUniversity.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ContosoUniversity.ViewModels
{
public class StudentViewModel
{
public int ID { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "First Name")]
public string FirstMidName { get; set; }
[Display(Name = "Enrollment Date")]
[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
[Display(Name = "Date Of Birth")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
public string FullName
{
get
{
return FirstMidName + LastName;
}
}
public virtual ICollection<Enrollment> Enrollments { get; set; }
public List<Comment> Comments { get; set; }
}
}
View:
#model PagedList.IPagedList<ContosoUniversity.ViewModels.StudentViewModel>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Students";
}
<h2>Students</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm("Index", "Student", FormMethod.Get))
{
<p>
Find by name: #Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
</p>
}
<table class="table">
<tr>
<th>
#Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm })
</th>
<th>
First Name
</th>
<th>
#Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm })
</th>
<th>
Date Of Birth
</th>
<th>
Full Name
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstMidName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EnrollmentDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateOfBirth)
</td>
<td>
#Html.DisplayFor(modelItem => item.FullName)
</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>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
I think something might be wrong with view model or automapper if need some more code please write to me!

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.