Sorting date using KnockoutJS - c#

Firstly, I'd like to thank you for reading this post.
I have a small problem, I am trying to sort my posts in descending order of date created. It sorts the date in descending order by the posts created today and yesterday get mixed up.
For example: Posts created show as;
Created: Today, Created: Yesterday, Created: 29/09/2015, Created: 28/09/2015
After sorting they're displayed in this order:
Created: Yesterday,
Created: Today,
Created: 29/09/2015,
Created: 28/09/2015,
The code I am using is shown below
foreach.Posts.sort(function (l, r) { return l.Created() > r.Created() ? -1 : 1 })
Is there a way around this ?
Thank you.
Updated: Added C# Class
[HttpGet]
public LivePostModel GetPosts(string id, string page = null, string startDate = "", string endDate = "")
{
Thread thread = _threadManager.GetThreadByDomain(id);
if (thread == null)
return new LivePostModel();
DateTime? dtDateFrom = null;
DateTime? dtDateTo = null;
if (string.IsNullOrEmpty(startDate) == false)
dtDateFrom = DateTime.Parse(startDate);
if (string.IsNullOrEmpty(endDate) == false)
dtDateTo = DateTime.Parse(endDate);
PostWithCount posts = _postManager.GetPosts(new PostsFilter
{
SubDomain = id,
Page = string.IsNullOrEmpty(page) ? 0 : int.Parse(page),
StartDate = dtDateFrom,
EndDate = dtDateTo
});
IOrderedEnumerable<Post> sortedPosts = posts.Items.OrderByDescending(x => x.Created);
var postsModel = new List<PostModel>();
List<string> userKeys = sortedPosts
.Select(obj => obj.CreatedByUserId)
.Distinct()
.ToList();
IList<User> users = _userManager.GetUsersByKeys(userKeys);
foreach (Post post in sortedPosts)
{
User user = users.FirstOrDefault(u => u.Key == post.CreatedByUserId);
if (user != null)
{
PostModel postModel = Mapper.Map<Post, PostModel>(post);
postModel.User = GetUserDetails(postModel.User, user);
postsModel.Add(postModel);
}
}
var model = new LivePostModel
{
Posts = postsModel.ToList(),
CountPages = posts.Count.ToString(CultureInfo.InvariantCulture),
CountItems = posts.CountItems.ToString(CultureInfo.InvariantCulture),
CurrentId = thread.Key,
Subdomain = thread.Subdomain,
CurrentUserName = UserContextService.IsAuthenticated ? UserContextService.Key : String.Empty,
OwnerThreadName = thread.OwnerUserId,
OwnerThreadFullName = string.Format("{0} {1}", thread.FirstName, thread.LastName),
CanAddPost = _threadManager.IsCurrentUserCanUploadContent(thread)
};
model.CurrentUserCanDelete = CheckIfUserCanDeletePost(thread);
return model;
}
JSON Data:
"Posts":[
{"Key":"Post_ab780bb71",
"Header":null,
"Message":"Post details go here ",
"PostId":"Post_11338",
"Created":"today",
"Modified":"today",
"User":{ User Details below }

Yes, however you'll need to make some changes...
You need to use a sortable time format... For example, 2015-10-02T10:09:56.
I assume the posts have a property called CreatedOn which indicate whether it was posted today yesterday etc... Add another property called CreatedOnSortable that includes the actual DateTime in the format show, you can do this by calling ToString('s') on the DateTime...
DateTime.UtcNow.ToString("s");
Edit
HomeController
public ActionResult Index()
{
var livePostModel = new PostsViewModel
{
Posts = new Post[]
{
new Post
{
Created = "Today",
CreatedDateTime = DateTime.UtcNow,
Header = "Todays Post",
Key = Guid.NewGuid().ToString(),
Message = "Todays message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
new Post
{
Created = "Yesterday",
CreatedDateTime = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
Header = "Yesterdays Post",
Key = Guid.NewGuid().ToString(),
Message = "Yesterdays message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
new Post
{
Created = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)).ToString("D"),
CreatedDateTime = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)),
Header = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)).ToString("D") + " Post",
Key = Guid.NewGuid().ToString(),
Message = DateTime.UtcNow.Subtract(TimeSpan.FromDays(2)).ToString("D") + " message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
new Post
{
Created = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)).ToString("D"),
CreatedDateTime = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)),
Header = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)).ToString("D") + " Post",
Key = Guid.NewGuid().ToString(),
Message = DateTime.UtcNow.Subtract(TimeSpan.FromDays(3)).ToString("D") + " message",
Modified = string.Empty,
PostId = Guid.NewGuid().ToString()
},
}
};
this.ViewBag.Json = JsonConvert.SerializeObject(livePostModel);
return View();
}
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<div class="row" data-bind="foreach: posts">
<div class="col-md-6" data-bind="text: Created"></div>
<div class="col-md-6" data-bind="text: CreatedSortable"></div>
</div>
<div class="row">
<div class="col-md-6"><button data-bind="click: orderByAsc">Order Ascending</button></div>
<div class="col-md-6"><button data-bind="click: orderByDesc">Order Descending</button></div>
</div>
#section scripts{
<script src="~/Scripts/knockout-3.3.0.js" type="text/javascript"></script>
<script type="text/javascript">
var json = #this.Html.Raw(this.ViewBag.Json);
function Post(post) {
var self = this;
self.key = ko.observable(post.Key || '');
self.header = ko.observable(post.Header || '');
self.message = ko.observable(post.Message || '');
self.postId = ko.observable(post.PostId || '');
self.created = ko.observable(post.Created || '');
self.createdSortable = ko.observable(post.CreatedSortable || '');
self.modified = ko.observable(post.Modified || '');
}
function PostsViewModel(model)
{
var self = this;
self.posts = ko.observableArray(model.Posts);
self.orderByAsc = function() {
self.posts.sort(function(left, right) { return left.CreatedSortable == right.CreatedSortable ? 0 : (left.CreatedSortable < right.CreatedSortable ? 1:-1 ) });
}
self.orderByDesc = function() {
self.posts.sort(function(left, right) { return left.CreatedSortable == right.CreatedSortable ? 0 : (left.CreatedSortable < right.CreatedSortable ? -1: 1 ) });
}
}
ko.applyBindings(new PostsViewModel(json));
</script>
}
Result
Ascending
Descending

Related

There is no ViewData item of type 'IEnumerable' that has the key 'Conve'

I am making a tweak to an app and doing an UPDATE. It throws me the following error:
There is no ViewData item of type 'IEnumerable' that has the key 'Conve'.
My DropDownList loads the data perfectly but when I select any of that list to use its value and change it to the value that is in my BD it throws that error
Model: TableAsign.cs
public class TableAsign
{
public long IdCliente { get; set; }
public string nombre { get; set; }
}
Controller: MastController.cs
[Authorize]
public ActionResult Asign_Conv(int idUsuario)
{
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{ return new SelectListItem()
{ Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
using (TPConveniosEntities db = new TPConveniosEntities())
{
Usuario user = db.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
return View(user);
}
}
In this part it performs the UPDATE and it seems to me that it has to do when I bring the value of my DropDownList with my long variable, it throws me the error and then when I consult my DB I see that if it performs the UPDATE but giving me that error
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IdCliente = Convert.ToInt32(collection["Convenio"].Trim());
user.userName = userName;
user.idCliente = IdCliente;
contexto.SaveChanges();
return View(user);
}
}
VIEW: Asign_Conv.cshtml
#using TPConvenios.App_Data;
#model Usuario
#{
Layout = null;
AjaxOptions ajaxOpciones = new AjaxOptions
{
UpdateTargetId = "cuerpoPopUpGenerico2",
InsertionMode = InsertionMode.Replace,
OnSuccess = "OnSuccess_Asign",
OnFailure = "OnFailure"
};
List<SelectListItem> items = (List<SelectListItem>)ViewBag.items;
}
<div id="contenedor" style="margin: 15px 30px">
#using (Ajax.BeginForm("Asign_Conv", "Mast", null, ajaxOpciones, new { id = "Asign_Conv" }))
{ #Html.ValidationSummary(true);
<input type="hidden" name="idUsuario" id="idUsuario" value="#(null != Model ? Model.idUsuario : 0)" />
<p>
<input name="usuario" type="text" id="usuario" class="usuario" placeholder="Usuario" value="#(null != Model ? Model.userName : String.Empty)"/>
</p>
<p>
#Html.DropDownList("Convenio", items, "Seleccione el Convenio", new { #class = "form-control" })
</p>
<p id="bot">
<input name="submit" type="submit" id="submit" value="Asignar" class="botonNuevo" style="float: right" />
</p>
}
</div>
I managed to solve my problem by bringing me the code with which I load my DropdownList, and pasting it to the POST where it performs UPDATE.
staying this way
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IDCliente = Convert.ToInt32(collection["Conve"].Trim());
/*********** ESTO FUE LO QUE COPIE PARA QUE FUNCIONARA **********/
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{
return new SelectListItem()
{
Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
/*************************** HASTA AQUI **********************/
user.userName = userName;
user.idCliente = IDCliente;
contexto.SaveChanges();
return View(user);
}
}

How to integrate stripe payment with custom form in ASP.NET MVC? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How do I use custom stripe form and then integration with 3D Security options using ASP.NET MVC?
Custom Form Design using Razor/ Html
<div class="campagin_start content" style="max-width:100%">
<div class="cell example example2" id="">
<form>
<div class="row">
<div class="field">
<div id="example2-card-number" class="input empty"></div>
<label for="example2-card-number" data-tid="elements_examples.form.card_number_label">Card number</label>
<div class="baseline"></div>
</div>
</div>
<div class="row">
<div class="field half-width">
<div id="example2-card-expiry" class="input empty"></div>
<label for="example2-card-expiry" data-tid="elements_examples.form.card_expiry_label">Expiration</label>
<div class="baseline"></div>
</div>
<div class="field half-width">
<div id="example2-card-cvc" class="input empty"></div>
<label for="example2-card-cvc" data-tid="elements_examples.form.card_cvc_label">CVC</label>
<div class="baseline"></div>
</div>
</div>
<button id="card-button">#WebResources.Donate $#Model.budget</button>
Cancel
</form>
<p id="payment-result"><!-- we'll pass the response from the server here --></p>
</div>
</div>
Script
var stripe = Stripe('#ViewBag.StripePublishKey');
var elementStyles = {
base: {
color: '#32325D',
fontWeight: 500,
fontFamily: 'Source Code Pro, Consolas, Menlo, monospace',
fontSize: '16px',
fontSmoothing: 'antialiased',
'::placeholder': {
color: '#CFD7DF',
},
':-webkit-autofill': {
color: '#e39f48',
},
},
invalid: {
color: '#E25950',
'::placeholder': {
color: '#FFCCA5',
},
},
};
var elementClasses = {
focus: 'focused',
empty: 'empty',
invalid: 'invalid',
};
var elements = stripe.elements({
fonts: [
{
cssSrc: 'https://fonts.googleapis.com/css?family=Source+Code+Pro',
},
],
// Stripe's examples are localized to specific languages, but if
// you wish to have Elements automatically detect your user's locale,
// use `locale: 'auto'` instead.
locale: window.__exampleLocale
});
var Id = #Html.Raw(Json.Encode(Model.Id)); // Get Id From Model
var cardNumber = elements.create('cardNumber', {
showIcon: true,
style: elementStyles,
classes: elementClasses,
});
cardNumber.mount('#example2-card-number');
var cardExpiry = elements.create('cardExpiry', {
style: elementStyles,
classes: elementClasses,
});
cardExpiry.mount('#example2-card-expiry');
var cardCvc = elements.create('cardCvc', {
style: elementStyles,
classes: elementClasses,
});
cardCvc.mount('#example2-card-cvc');
var formClass = '.example2';
var example = document.querySelector(formClass);
var form = example.querySelector('form');
var resultContainer = document.getElementById('payment-result');
// Payment Button Handle
form.addEventListener('submit', function (event) {
$('#AjaxLoader').show();
event.preventDefault();
resultContainer.textContent = "";
stripe.createPaymentMethod({
type: 'card',
card: cardNumber,
}).then(handlePaymentMethodResult);
});
function handlePaymentMethodResult(result) {
if (result.error) {
$('#AjaxLoader').hide();
$("#canceltran").show();
// An error happened when collecting card details, show it in the payment form
resultContainer.textContent = result.error.message;
} else {
// Otherwise send paymentMethod.id to your server
fetch('/cart/pay', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ PaymentMethodId: result.paymentMethod.id, Id: Id})
}).then(function (result) {
return result.json();
}).then(handleServerResponse);
}
}
function handleServerResponse(responseJson) {
if (responseJson.error) {
// An error happened when charging the card, show it in the payment form
resultContainer.textContent = responseJson.error;
$('#AjaxLoader').hide();
$("#canceltran").show();
} else if (responseJson.requiresAction) {
// Use Stripe.js to handle required card action
stripe.handleCardAction(
responseJson.clientSecret
).then(function (result) {
if (result.error) {
$('#AjaxLoader').hide();
resultContainer.textContent = result.error.message;
$("#canceltran").show();
// Show `result.error.message` in payment form
} else {
// The card action has been handled
// The PaymentIntent can be confirmed again on the server
fetch('/cart/pay', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ PaymentIntentId: result.paymentIntent.id, Id:Id })
}).then(function (confirmResult) {
return confirmResult.json();
}).then(handleServerResponse);
$('#AjaxLoader').hide();
}
});
}
else {
// Show a success message or Required action
}
}
Controller -In Constructor, you have to use your Stripe Credentials
public class CartController : ControllerBase
{
public CartController()
{
StripeConfiguration.ApiKey = YOUR API KEY; // Replace your API KEY here
}
string stripePublishKey = YOUR PUBLISHER KEY; // Replace your PUBLISHER KEY here
private class StripeDataReq
{
public string PaymentMethodId { get; set; }
public string PaymentIntentId { get; set; }
public string Id { get; set; }
}
public async Task<ActionResult> Pay(StripeDataReq stripeDataReq)
{
// From Id you can get the value
var cart = await Cart.Table.LookupAsync(stripeDataReq.Id);
// We set amount (amout*100) because here amount consider in cent (100 cent charge $1) so
var amount = cart.Budget * 100;
var email = ""; // Set Email Id for payment Receiver
var service = new PaymentIntentService();
PaymentIntent paymentIntent = null;
try
{
if (stripeDataReq.PaymentMethodId != null)
{
// Create the PaymentIntent
var options = new PaymentIntentCreateOptions
{
Description = cart.Desc,
PaymentMethod = stripeDataReq.PaymentMethodId,
//Shipping is not nessasery for every region this is useful for an Indian Standard
//Shipping = new ChargeShippingOptions
//{
// Name = giver.Name,
// Address = new AddressOptions
// {
// Line1 = "510 Townsend St",
// PostalCode = "98140",
// City = "San Francisco",
// State = "CA",
// Country = "US",
// },
//},
ReceiptEmail = email,
Amount = amount,
Currency = "usd",
Confirm = true,
//ErrorOnRequiresAction = true,
ConfirmationMethod = "manual",
};
paymentIntent = service.Create(options);
}
if (stripeDataReq.PaymentIntentId != null)
{
var confirmOptions = new PaymentIntentConfirmOptions { };
paymentIntent = service.Confirm(
stripeDataReq.PaymentIntentId,
confirmOptions
);
}
}
// StripeException handle all types of failure error and then return the message into FE
catch (StripeException e)
{
return Json(new { error = e.StripeError.Message });
}
TempData["Id"] = stripeDataReq.Id;
return await generatePaymentResponse(paymentIntent);
}
//For 3D secure card
private async Task<ActionResult> generatePaymentResponse(PaymentIntent intent)
{
var CartId = TempData["Id"];
if (intent.Status.ToString().ToLower() == "succeeded")
{
// Handle post-payment fulfillment
return Json(new { success = true });
}
// requires_action means 3d secure card required more authentications for payment
else if (intent.Status == "requires_action")
{
// Tell the client to handle the action
return Json(new
{
requiresAction = true,
clientSecret = intent.ClientSecret
});
}
else
{
// Any other status would be unexpected, so error
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Invalid PaymentIntent status");
}
}
}
Here is my working code with custom form integration using stripe payment, hope this post will help many developers

can I use one controller method in js?

I need help to get a solution to a question. The case is as follows:
We are working on a group project with asp.net, c #, javascript, html and razor technologies.
The structure of projects within the solution is as follows:
1.POJO-entities: where the models are located.
2.DataAccess: it is divided into three folders: 1. Crud (where are the classes that contain the "crudfactory" of each Pojo, 2. Dao (find the connection to the database, in this case SQL Server) and finally, the Mapper
3.CoreApi, where are the managers of each well.
4.WebApi, where are the controllers of each well.
5.WepApp, where is the UI (cshtmls) and javascripts.
Now, I have to implement a virtual wallet that can be topped up via PayPal and I have a method that receives the price and the description of the payment, for now it is "burned", but it must be parameterizable. I want to know if I can take the value of CtrlInput and put it in the HTMLAtributes of my ActionLink.
The idea may remove the # Html.ActionLink and leave the functionality in the "Update", but I don't know how to send the parameters from the view JS to the PayPal controller.
This is the javascript code for the wallet view:
function vMonedero() {
//this.tblMonederoId = 'tblMonedero';
this.service = 'monedero';
this.ctrlActions = new ControlActions();
this.columns = "IdUsuario, IdMonedero, Monto";
this.paypal = new PaymentWithPayPal();
this.RetrieveAll = function () {
this.ctrlActions.FillTable(this.service, this.tblMonedero, false);
}
this.Create = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
if (monederoData["Monto"] == "") {
this.ctrlActions.ShowMessage('E', "Favor ingresar el nuevo valor");
}
else if (isNaN(monederoData["Monto"])) {
this.ctrlActions.ShowMessage('E', "Favor ingresar un valor numérico");
}
else {
this.ctrlActions.PostToAPI(this.service, monederoData);
}
}
this.Update = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
price = monederoData["Monto"];
paypal.PaymentWithPayPal(price, "Recarga de monedero");
//Hace el post al create
this.ctrlActions.PutToAPI(this.service, monederoData);
//Refresca la tabla
}
this.Delete = function () {
var monederoData = {};
monederoData = this.ctrlActions.GetDataForm('frmEdition');
//Hace el post al create
this.ctrlActions.DeleteToAPI(this.service, monederoData);
//Refresca la tabla
}
this.BindFields = function (data) {
this.ctrlActions.BindFields('frmEdition', data);
}
}
//ON DOCUMENT READY
$(document).ready(function () {
var vmonedero = new vMonedero();
//vmonedero.RetrieveAll();
});
This is the view code:
#using WebApp.Helpers;
<script src="~/Scripts/Views/vMonedero.js"></script>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="card border-secondary" style="margin-top: 50px;">
<div class="card-header">
<div class="row pull-right">
<div class="col-md-8">Monedero</div>
<div class="col-md-4">
#Html.CtrlButton(viewName: "vMonedero", id: "btnCreate", label: "Crear", onClickFunction: "Create", buttonType: "success")
#Html.CtrlButton(viewName: "vMonedero", id: "btnUpdate", label: "Recargar", onClickFunction: "Update", buttonType: "info")
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<div class="bs-component">
<form id="frmEdition">
#Html.CtrlInput(id: "txtIdUsuario", type: "text", label: "N° de identificación", columnDataName: "IdUsuario")
#Html.CtrlInput(id: "txtIdMonedero", type: "text", label: "N° de monedero", columnDataName: "IdMonedero")
#Html.CtrlInput(id: "txtIdMonto", type: "text", label: "Monto", columnDataName: "Monto")
#* #Html.CtrlDropDown(id: "drpGender", label: "Gender", listId: "LST_GENERO")*#
</form>
</div>
</div>
</div>
</div>
</div>
#*<script>
$('#price').click(function () {
var monederoData = {};
ctrlActions = new ControlActions();
ctrlActions.GetDataForm('frmEdition');
monederoData["Monto"] = price;
return price;
});
</script>*#
Paypal Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PaymentPayPal.Models;
using PayPal.Api;
namespace WebApp.Controllers
{
public class PayPalController : Controller
{
// GET: PayPal
public ActionResult Index()
{
return View();
}
public ActionResult PaymentWithPaypal(string price, string product)
{
//getting the apiContext as earlier
APIContext apiContext = ConfigurationPayPal.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
"/Paypal/PaymentWithPayPal?";
var guid = Convert.ToString((new Random()).Next(100000));
var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid, price, product);
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = null;
while (links.MoveNext())
{
Links lnk = links.Current;
if (lnk.rel.ToLower().Trim().Equals("approval_url"))
{
paypalRedirectUrl = lnk.href;
}
}
Session.Add(guid, createdPayment.id);
Console.WriteLine(createdPayment.id);
return Redirect(paypalRedirectUrl);
}
else
{
var guid = Request.Params["guid"];
Console.WriteLine("Session:" + Session[guid] as string);
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("FailureView");
}
}
}
catch (Exception ex)
{
return View("FailureView");
}
return View("SuccessView");
}
private PayPal.Api.Payment payment;
private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
{
var paymentExecution = new PaymentExecution() { payer_id = payerId };
this.payment = new Payment() { id = paymentId };
return this.payment.Execute(apiContext, paymentExecution);
}
private Payment CreatePayment(APIContext apiContext, string redirectUrl, string price, string product)
{
var itemList = new ItemList() { items = new List<Item>() };
itemList.items.Add(new Item()
{
name = product,
currency = "USD",
price = price,
quantity = "1",
sku = "sku"
});
var payer = new Payer() { payment_method = "paypal" };
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
// similar as we did for credit card, do here and create details object
var details = new Details()
{
tax = "1",
shipping = "1",
subtotal = price
};
// similar as we did for credit card, do here and create amount object
var amount = new Amount()
{
currency = "USD",
total = "" + (int.Parse(price) + 1 + 1), // Total must be equal to sum of shipping, tax and subtotal.
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = "Transaction description.",
invoice_number = Convert.ToString((new Random()).Next(100000)),
amount = amount,
item_list = itemList
});
this.payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
// Create a payment using a APIContext
return this.payment.Create(apiContext);
}
}
}

How To Set Value To Drop-down list

I am using jQuery to set the second dropdown list items on selection of the first dropdown. At the time of edit action I want to set fetched data to the second dropdown list. I want to set ViewBag.UserLinkedList to the second dropdown list.
View:
<div class="form-row">
<div class="col-lg-7">
#Html.Label("User Type") #Html.DropDownListFor(m => m.LoginUserTypeID(SelectList)ViewBag.LoginUserTypeList, "--- Select User Type ---", new { #class = "form-control" })
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
#Html.Label("Parent User") #Html.DropDownListFor(m => m.UserLinkedID, new SelectList(""), "--- Select ---", new { #class = "form-control" })
</div>
<script>
$(document).ready(function() {
$("#LoginUserTypeID").change(function() {
$.get("/User/GetParentUserList", {
UserTypeID: $("#LoginUserTypeID").val()
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
})
});
</script>
Controller:
public JsonResult GetParentUserList(int UserTypeID)
{
List<V_Dealer_DealerEmployee> LinkedIDList = new List<V_Dealer_DealerEmployee>();
if (UserTypeID == 1 || UserTypeID == 2)
{
var d = from s in db.VDNSEmployeeMaster
select new
{
Id = s.EmpId,
Name = s.FirstName + " " + s.MiddleName + " " + s.LastName
};
d.ToList();
return Json(d.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
var unionAll = (from word in db.VDNSDealer select new
{
Id = word.m_code,
Name = word.institute_name
}).Concat(from word in db.DealerEngineerMaster select new {
Id = word.EnggId,
Name = word.EngineerName
});
return Json(unionAll.ToList(), JsonRequestBehavior.AllowGet);
}
}
Edit Action
public ActionResult Edit(int id)
{
var user = db.Users.SingleOrDefault(c => c.Id == id);
if (user == null)
return HttpNotFound();
List<LoginUserType> LoginUserTypeList = db.LoginUserType.ToList();
ViewBag.LoginUserTypeList = new SelectList(LoginUserTypeList, "UserTypeId", "UserTypeName");
List<V_Dealer_DealerEmployee> UserLinkedList = db.VDealerDealerEmployee.ToList();
ViewBag.UserLinkedList = new SelectList(UserLinkedList, "Id", "Name");
return View("New", user);
}
After returning view from edit action, you need to call your change function of LoginUserTypeID. Here is the required js for you
function UpdateUserLinkedIdDropdown(){
var userTypeId = $("#LoginUserTypeID").val();
//This check is for no options selected in LoginUserTypeID Dropdown
if(userTypeId === null || userTypeId === "" || userTypeId === undefined)
userTypeId = 0;
$.get("/User/GetParentUserList", {
UserTypeID: userTypeId
}, function(data) {
$("#UserLinkedID").empty();
$.each(data, function(index, row) {
$("#UserLinkedID").append("<option value='" + row.Id + "'>" + row.Name + "</option>")
});
});
}
$("#LoginUserTypeID").change(function() {
UpdateUserLinkedIdDropdown();
});
// Call it initially when view loaded
// You can do it in this way
UpdateUserLinkedIdDropdown();
// OR This way
$("#LoginUserTypeID").trigger('change');
Give it a try! I think this will work. If not comment plz

How to show an empty dropdownlist when another one isn't selected

I have two dropdownlists both connected to the database, one is called Distritos and the other is called Concelhos, while distritos isn´t selected, concelhos should show empty, when the user selects one of the words of distritos, the Concelhos should show. I want to make it like a state-City relation.
This is what i have in my controller:
public ActionResult getcidades(int? distrito = null)
{
var concelho =
Db.Concelhos.OrderBy(r => r.Nome) as IQueryable<Concelho>;
if (distrito != null)
{
concelho = concelho.Where(t => t.Distritos.Id == distrito);
}
return Json(concelho.Select(r => new { Nome = r.Nome, r.Id }), JsonRequestBehavior.AllowGet);
}
This is what i have in my view:
$("#Distrito").on("change", function() {
var valor = $(this).val();
$.ajax({
type: "get",
url: "#Url.Action("
getcidades ","
PiHelper ")",
data: {
distrito: valor
}
})
.done(function(concelho) {
var dropdown = $("#Concelho");
dropdown.empty().focus();
console.log(concelho, dropdown)
for (var i = 0; i < concelho.length; i++) {
$("<option>")
.attr("value", concelho[i].Id)
.text(concelho[i].Nome)
.appendTo(dropdown);
}
})
})
Try this:
$('#distritos').each(function() {
if ($(this).not(':selected'))
{
$('#concelhos').val(0);
}
});
or
if ($('#distritos :selected').length == 0)
{
$('#concelhos options').remove();
}

Categories