Using an MVC SelectList in webforms - asp.net

I would like to have grouped items within an asp.net dropdownlist and I thought of using the SelectList functionality from MVC to my webforms project. Here's what I have tried and the result. Can you help please with the binding?
<asp:DropDownList runat="server" id="ddlGroupBySelGeo" AutoPostBack="True"
DataTextField="Text" DataValueField="Value"
SelectMethod="GetMapItems" OnSelectedIndexChanged="ddlGroupBySelGeo_OnSelectedIndexChanged">
</asp:DropDownList>
public SelectList GetMapItems(object sender, EventArgs e)
{
var items = new List<SelectListItem>();
var group1 = new SelectListGroup() { Name = "Select" };
var group2 = new SelectListGroup() { Name = "Group" };
items.Add(new SelectListItem() { Text = "display selected", Value = "select", Group = group1 });
items.Add(new SelectListItem() { Text = GetLocalResourceObject("Region").ToString(), Value = "Regional", Group = group2 });
items.Add(new SelectListItem() { Text = GetLocalResourceObject("Municipality").ToString(), Value = "Municipio", Group = group2 });
items.Add(new SelectListItem() { Text = GetLocalResourceObject("Locality").ToString(), Value = "Localidade", Group = group2 });
items.Add(new SelectListItem() { Text = GetLocalResourceObject("Neighborhood").ToString(), Value = "Bairro", Group = group2 });
return new SelectList(items);
}

Have you tried setting the Value and Text parameters in the SelectList before you return it?
return new SelectList(items, "Value", "Text");

Related

PayPal Plus stay on own page

I have implemented a small PayPal PLUS Demo in ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
var config = ConfigManager.Instance.GetProperties();
config.Add("clientId", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("clientSecret", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("mode", "sandbox");
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var itemList = new ItemList() { items = new List<Item>() { new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" } } };
var payer = new Payer() { payment_method = "paypal" };
var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
var guid = Convert.ToString((new Random()).Next(100000));
var redirectUrl = baseURI + "guid=" + guid;
var redirUrls = new RedirectUrls() { cancel_url = redirectUrl + "&cancel=true", return_url = redirectUrl };
var details = new Details() { tax = "15", shipping = "10", subtotal = "75" };
var amount = new Amount() { currency = "USD", total = "100.00", details = details };
var transactionList = new List<Transaction> { new Transaction() { description = "Transaction description.", invoice_number = new Random().Next(999999).ToString(), amount = amount, item_list = itemList } };
var payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls };
var createdPayment = payment.Create(apiContext);
var approval_url = createdPayment.links.FirstOrDefault(x => x.rel == "approval_url").href;
hfApprovalUrl.Value = approval_url;
}
<asp:HiddenField runat="server" id="hfApprovalUrl"/>
<script src="https://www.paypalobjects.com/webstatic/ppplus/ppplus.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="ppplus"></div>
<script type="application/javascript">
var approval_url = $('#hfApprovalUrl').val();
var ppp = PAYPAL.apps.PPP({
"approvalUrl": approval_url,
"placeholder": "ppplus",
"mode": "sandbox",
"country": "DE"
});
</script>
Its works so far but if a choose a pay option (e.g. credit card) I will be redirected to PayPal.I want that the user stys on my own page. How can I do this?
Thanks!
Jan

MVC drop down list input post value and name

I'm writing a form which uses drop down menus for value selection. I'd like to know if it is possible to post Value and Name of the SelectList back to the Controller or add values for every list item? I need to set LateralityId = Value and LateralityName = Text.
I'll just post some snippets of the code to get the idea across. The model I'm using is
public class Condition
{
public string LateralityName { get; set; }
public string LateralityId { get; set; }
}
and the values are posted with
#Html.DropDownListFor( m => m.Condition.LateralityId, GetLateralities() )
where
public static List<SelectListItem> GetLateralities()
{
return new List<SelectListItem>
{
new SelectListItem { Text = "", Value = "900" },
new SelectListItem { Text = "Left", Value = "1001" },
new SelectListItem { Text = "Right", Value = "1002" },
new SelectListItem { Text = "Midline", Value = "1003" },
new SelectListItem { Text = "Left Midline", Value = "1004" },
new SelectListItem { Text = "Right Midline",Value = "1005" },
new SelectListItem { Text = "Both Sides", Value = "1006" },
new SelectListItem { Text = "Unknown", Value = "990" },
new SelectListItem { Text = "Unspecified", Value = "997" },
new SelectListItem { Text = "N/A", Value = "999" },
};
}
Any help is much appreciated. Thanks!
Solution thanks to Stephen Muecke
In the controller I simply use
LateralityName = GetLateralities().FirstOrDefault( x => x.Value == m.Condition.LateralityId )?.Text;

Need to Retrieve data from dynamically added text boxes

I added text boxes dynamically in ASP.Net from server side. By using one example which is shown in followed link
http://www.dotnettips4u.com/2013/03/dynamically-creating-text-boxes-using-c.html.
But I couldn't find out how to retrieve values from those text boxes..
Please help me to come out from this..
Here I am posting my code also..
Client Side Code:
<asp:TextBox ID="NoOfPsngr" runat="server" />
<asp:Button ID="AddP" runat="server" Text="Add Passengers" OnClick="AddP_Click" />
<asp:Panel runat="server" ID="passengerdet">
</asp:Panel>
Server Side Code:
protected void AddP_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(NoOfPsngr.Text);
Table table = new Table();
table.ID = "PsngrTbl";
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
TableRow row = new TableRow();
TableCell namelblCell = new TableCell();
Label namelbl = new Label();
namelbl.Text = "Name";
TableCell nameTxtCell = new TableCell();
TextBox nameTxt = new TextBox();
TableCell typelblCell = new TableCell();
Label typelbl = new Label();
typelbl.Text = "Type";
TableCell typeSelectCell = new TableCell();
DropDownList typeSelect = new DropDownList();
ListItem adultItem = new ListItem();
adultItem.Text = "Adult";
adultItem.Value = "Adult";
typeSelect.Items.Add(adultItem);
ListItem childItem = new ListItem();
childItem.Text = "Child";
childItem.Value = "Child";
typeSelect.Items.Add(childItem);
ListItem infantItem = new ListItem();
infantItem.Text = "Infant";
infantItem.Value = "Infant";
typeSelect.Items.Add(infantItem);
TableCell etktlblCell = new TableCell();
Label etktlbl = new Label();
etktlbl.Text = "Eticket No";
TableCell etktTxtCell = new TableCell();
TextBox etktTxt = new TextBox();
//Adding.....
namelblCell.Controls.Add(namelbl);
typelblCell.Controls.Add(typelbl);
etktlblCell.Controls.Add(etktlbl);
nameTxtCell.Controls.Add(nameTxt);
typeSelectCell.Controls.Add(typeSelect);
etktTxtCell.Controls.Add(etktTxt);
nameTxt.ID = "PName" + i;
typeSelect.ID = "PType" + i;
etktTxt.ID = "ETkt" + i;
row.Controls.Add(namelblCell);
row.Controls.Add(nameTxtCell);
row.Controls.Add(typelblCell);
row.Controls.Add(typeSelectCell);
row.Controls.Add(etktlblCell);
row.Controls.Add(etktTxtCell);
table.Rows.Add(row);
}
passengerdet.Controls.Add(table);
}
use javascript like
$('#PsngrTbl').find('input[type=radio]').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue;
var controlName = $(this).attr('name');
if ($('[name=' + controlName + ']:checked').val() == undefined) {
oValue = "";
}
else {
oValue = $('[name=' + controlName + ']:checked').val();
}
});
$('#PsngrTbl').find('input[type=checkbox]').each(function (index, element) {
var o = $(this);
var value;
if (o.on == true) {
value = 1;
}
else {
value = 0;
}
var oID = o.attr("id");
var oValue = value;
});
$('#PsngrTbl').find('textarea').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
$('#PsngrTbl').find('select').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
It will return all values of controlls of that table

Asp.Net MVC WebGrid paging...is there an alternative to putting data in session?

I finally got my MVC WebGrid paging to work and my drop downlist box criteira to maintain state!! I did this by putting the result data and criteria data in session for when the 'next page' is click on the grid and everything could be re-populated. Is there another, more appropriate way to do this without loading up a bunch of session varables?
HERE IS MY CONTROLER CODE:
[HttpPost]
public ActionResult Results(TestCriteriaConsolidated form)
{
List<TestCriteriaResults> gridResults = new List<TestCriteriaResults>();
gridResults.Add(new TestCriteriaResults { Value1 = "one", Value2 = "one", Value3 = "three", Value4 = "Four" });
gridResults.Add(new TestCriteriaResults { Value1 = "one", Value2 = "two", Value3 = "three", Value4 = "four" });
gridResults.Add(new TestCriteriaResults { Value1 = "one", Value2 = "two", Value3 = "three", Value4 = "four" });
gridResults.Add(new TestCriteriaResults { Value1 = "one", Value2 = "two", Value3 = "three", Value4 = "four" });
gridResults.Add(new TestCriteriaResults { Value1 = "one", Value2 = "two", Value3 = "three", Value4 = "four" });
Session["GridResults"] = gridResults;
Session["SelectedYear"] = form.testCriteria.Year;
form.testCriteriaResults = gridResults;
return View(form);
}
[HttpGet]
public ActionResult Results()
{
List<TestCriteriaResults> gridResults = ((List<TestCriteriaResults>) Session["GridResults"]);
TestCriteria criteria = new TestCriteria() { Year = Session["SelectedYear"].ToString() };
TestCriteriaConsolidated combined = new TestCriteriaConsolidated { testCriteriaResults = gridResults, testCriteria = criteria };
return View(combined);
}
HERE IS CODE FROM MY PARIAL VIEW:
#using (Html.BeginForm("Results", "Home"))
{
<div style="float:left">
<div style="font-weight:bold">
#Html.LabelFor(m => m.testCriteria.Year)
</div>
<div style="width:110px; ">
#Html.DropDownListFor(m => m.testCriteria.Year, new SelectList(new[]
{
new SelectListItem{ Text="All Years", Value=" " },
new SelectListItem{ Text="2010", Value="2010" },
new SelectListItem{ Text="2009", Value="2009" },
new SelectListItem{ Text="2008", Value="2008" },
new SelectListItem{ Text="2007", Value="2007" },
new SelectListItem{ Text="2006", Value="2006" }
}, "Value", "Text", "1"), new { #style = "width: 100px; margin-top: 5px" })
</div>
</div>
<div style="float:left">
<div>
</div>
<div style="width:100px; ">
<input type="submit" value="Results" />
</div>
</div>
}
HERE IS MY VIEW CODE TO DISPLAY THE GRID WITH RESULTS:
#model MvcApplication1.Models.TestCriteriaConsolidated
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#if (Model == null || Model.testCriteriaResults == null)
{
}
else
{
var grid = new WebGrid(Model.testCriteriaResults,canPage: true, rowsPerPage: 2);
#grid.Pager(WebGridPagerModes.Numeric);
<div id="grid">
#grid.GetHtml()
</div>
}
Actually, there is an alternative. Make sure you get the selected year in a query string parameter and then you don't need a session variable to hold the data. The pager will then parese the query string parameter and appended it automatically to the pager links.
One way to do this is to
public ActionResult Search(string year)
{
return RedirectToAction("Index", "Results", new { searchString = year });
}
And make sure your results method accepts a string parameter (or whatever datatype you want).

How to test custom Model Binders in ASP.NET MVC?

I've written some custom model binders (implementing IModelBinder) in our ASP.NET MVC application. I'm wondering what is a good approach to unittest them (binders)?
I did it this way:
var formElements = new NameValueCollection() { {"FirstName","Bubba"}, {"MiddleName", ""}, {"LastName", "Gump"} };
var fakeController = GetControllerContext(formElements);
var valueProvider = new Mock<IValueProvider>();
var bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null);
private static ControllerContext GetControllerContext(NameValueCollection form) {
Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
mockRequest.Expect(r => r.Form).Returns(form);
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(mockRequest.Object);
return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
}
And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.
Here's a simple no-mocks way I wrote for you on my blog assuming you use the ValueProvider and not the HttpContext: http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
[TestMethod]
public void DateTime_Can_Be_Pulled_Via_Provided_Month_Day_Year_Hour_Minute_Second_Alternate_Names()
{
var dict = new ValueProviderDictionary(null) {
{ "foo.month1", new ValueProviderResult("2","2",null) },
{ "foo.day1", new ValueProviderResult("12", "12", null) },
{ "foo.year1", new ValueProviderResult("1964", "1964", null) },
{ "foo.hour1", new ValueProviderResult("13","13",null) },
{ "foo.minute1", new ValueProviderResult("44", "44", null) },
{ "foo.second1", new ValueProviderResult("01", "01", null) }
};
var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = dict };
DateAndTimeModelBinder b = new DateAndTimeModelBinder() { Month = "month1", Day = "day1", Year = "year1", Hour = "hour1", Minute = "minute1", Second = "second1" };
DateTime result = (DateTime)b.BindModel(null, bindingContext);
Assert.AreEqual(DateTime.Parse("1964-02-12 13:44:01"), result);
}
dict could be refactored like this
FormCollection form = new FormCollection
{
{ "month1", "2" },
{ "day1", "12" },
{ "year1", "1964" },
{ "hour1", "13" },
{ "minute1", "44" },
{ "second1", "01" }
};
var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = form.ToValueProvider() };

Resources