Controller:
public ActionResult ComboBox()
{
List<ComboBoxClass> Products = new List<ComboBoxClass>();
Products.Add(new ComboBoxClass { ProductName = "Masa" });
Products.Add(new ComboBoxClass { ProductName = "Sandalye" });
Products.Add(new ComboBoxClass { ProductName = "Bilgisayar" });
Products.Add(new ComboBoxClass { ProductName = "Laptop" });
Products.Add(new ComboBoxClass { ProductName = "Kulaklık" });
Products.Add(new ComboBoxClass { ProductName = "Bardak" });
Products.Add(new ComboBoxClass { ProductName = "Kalem" });
Products.Add(new ComboBoxClass { ProductName = "Seramik" });
Products.Add(new ComboBoxClass { ProductName = "Telefon" });
ViewData["Products"] = Products;
return View(Products);
}
View:
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "BenimComboBox";
settings.Width = 180;
settings.Properties.ValueField = "ProductName";
settings.SelectedIndex = -1;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
settings.Properties.DropDownStyle = DropDownStyle.DropDown;
settings.Properties.TextField = "ProductName";
settings.Properties.ValueField = "ProductName";
}
).BindList(ViewData["Products"]).GetHtml()
Class
public class ComboBoxClass
{
public string ProductName { get; set; }
}
I have products.I list all products on ComboBox.How can ı pass my SelectedIndexChanged value to ActionResult ?
I want to see selected value below " string SelectedItem "
public ActionResult SelectedItemHere(string SelectedItem)
{
// Processes..
return View();
}
You need to add below code to your Combobox,
settings.Properties.ClientSideEvents.SelectedIndexChanged = "SelectedId";
After that
Javascript Code in your layout
function SelectedId() {
var data= {
SelectedItem: BenimComboBox.GetValue(),
};
$.ajax({
url: "/YOUR CONTROLLER/YOUR ACTİONRESULT",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),
And Last,
Controller:
public ActionResult SelectedItemHere(string SelectedItem)
{
// Processes..
return View();
}
Access DevExpress ComboBox Selected Index by client side
function OnComboBoxSelectedIndexChanged(e, s) {
//check seleted index
var selected_index = e.lastSuccessValue;
alert(selected_index);
}
<dx:ASPxComboBox ID="cbsample" runat="server" AutoPostBack="true">
<ClientSideEvents SelectedIndexChanged="OnComboBoxSelectedIndexChanged" />
<Items>
<dx:ListEditItem Text="item name" Value="0" />
<dx:ListEditItem Text="item name1" Value="1" />
<dx:ListEditItem Text="item name2" Value="2" />
</Items>
</dx:ASPxComboBox>
Related
My problem is idk how to reflect in a label depending of input value in a entry field by a customer.
To make the things clear, let's start in our database.
Our database
Few information about our realtime database.
In our DELIVERY TABLE, we have 3 types of delivery(standard, reservation and express). In express, by the word itself, it's a rush delivery and we will require a DELIVERY FEE from the customer.
Another table is PRODUCT. We have 2 product for now, MINERAL(PROD1) AND SPARKLING(PROD2). The price of PROD1 is 35 ana PROD2 is 40.
What I've try right now is I put an SelectedIndexChanged in my picker delivery type and picker product type.
//This is my deliverytype event
private async void Picker_DeliveryType_SelectedIndexChanged(object sender, EventArgs e)
{
DELIVERY deliverySave = Picker_DeliveryType.SelectedItem as DELIVERY;
var selectedDeliveryItem = deliverySave.deliveryType;
var note = deliverySave.deliveryFee;
if(selectedDeliveryItem == "Express")
{
await DisplayAlert("Note", "Estimated Delivery: 2 hours from now", "OK");
labelDeliveryFee.Text = "Delivery Fee:" + note;
entryfieldReservationDate.IsEnabled = false;
}
else if(selectedDeliveryItem == "Standard")
{
await DisplayAlert("Note", "Within the day", "OK");
entryfieldReservationDate.IsEnabled = true;
}
else
{
await DisplayAlert("Note", "Enter Reservation Date", "OK");
entryfieldReservationDate.IsEnabled = true;
}
}
//This is my product type event
private void Picker_ProductType_SelectedIndexChanged(object sender, EventArgs e)
{
PRODUCT prod = Picker_ProductType.SelectedItem as PRODUCT;
var selectedProductItem = prod.productType;
var productPricing = prod.productPrice;
if (selectedProductItem == "Mineral")
{
labelProductPrice.Text = Convert.ToString(productPricing);
}
else
{
labelProductPrice.Text = Convert.ToString(productPricing);
}
}
AND my expected output is I want the 2 SelectedIndexChanged will put inside my order button.
//this is my order button click functio now
async private void Button_Clicked(object sender, EventArgs e)
{
if (selectedDeliveryType == "Standard")
{
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
else if (selectedDeliveryType == "Reservation")
{
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
else
{
int deliveryfee = deliverySave.deliveryFee;
if (selectedProductItem == "Mineral")
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
else
{
//some code here
waterOrder.orderTotalAmount = totalprice;
}
}
//some code here
var SaveData = await waterorderRepos.Save(waterOrder);
var SaveDataToCustomerNotification = await waterorderRepos.SaveCustomerNotification(customerNotification);
if (SaveData)
{
await this.DisplayAlert("Order", "Order successfully", "OK");
ClearData();
CloseAllPopup();
return;
}
else
{
await this.DisplayAlert("Order", "We cannot process your order at the moment.", "OK");
}
}
I will show you some visual presentation between my work now and my expected output.
This is the image.
Please help me guys, idk how to it.Also, no MVVM please cause IDK how to do it. Thank you so much.
Based on the complexity of your code, I recommend that you use the MVVM pattern for implementation.
I created a demo and achieved your function.
You can refer to the following code:
1.create a view model MyViewModel.cs
public class MyViewModel: INotifyPropertyChanged
{
public ObservableCollection<Delivery> Deliveries { get; set; }
private Delivery _deliverySelectedItem;
public Delivery DeliverySelectedItem
{
get => _deliverySelectedItem;
set {
SetProperty(ref _deliverySelectedItem, value);
// update the TotalAmount
caculateTotalAmount();
}
}
public ObservableCollection<Product> Products { get; set; }
//add SelectedItem here
private Product _productSelectedItem;
public Product ProductSelectedItem
{
get => _productSelectedItem;
set {
SetProperty(ref _productSelectedItem, value);
// update the TotalAmount
caculateTotalAmount();
}
}
private int _quantity;
public int Quantity
{
get => _quantity;
set
{
SetProperty(ref _quantity, value);
// update the TotalAmount
caculateTotalAmount();
}
}
private int _totalAmount;
public int TotalAmount
{
get => _totalAmount;
set
{
SetProperty(ref _totalAmount, value);
}
}
private void caculateTotalAmount() {
if (String.IsNullOrEmpty(Quantity.ToString() ) || Quantity == 0) {
TotalAmount = 0;
return;
}
if (ProductSelectedItem!=null && DeliverySelectedItem!=null) {
TotalAmount = ProductSelectedItem.productPrice * Quantity + DeliverySelectedItem.deliveryFee;
}
}
public MyViewModel() {
Products = new ObservableCollection<Product>();
Products.Add(new Product { ProductId = 01, productType = "Products", productPrice = 10 });
Products.Add(new Product { ProductId = 02, productType = "02", productPrice = 12 });
Products.Add(new Product { ProductId = 03, productType = "Products", productPrice = 13 });
Products.Add(new Product { ProductId = 04, productType = "Products", productPrice = 15 });
Deliveries = new ObservableCollection<Delivery>();
Deliveries.Add(new Delivery { deliveryFee = 10, deliveryType = "Express" });
Deliveries.Add(new Delivery { deliveryFee = 20, deliveryType = "Standard" });
Deliveries.Add(new Delivery { deliveryFee = 30, deliveryType = "Standard" });
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
2.create class Delivery.cs and Product.cs
public class Delivery
{
public string deliveryType { get; set; }
public int deliveryFee { get; set;}
}
public class Product
{
public int ProductId { get; set; }
public string productType { get; set; }
public int productPrice { get; set; }
}
3.MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pickerapp2023112="clr-namespace:PickerApp2023112"
x:Class="PickerApp2023112.MainPage">
<ContentPage.BindingContext>
<pickerapp2023112:MyViewModel></pickerapp2023112:MyViewModel>
</ContentPage.BindingContext>
<StackLayout>
<Picker x:Name="Picker_DeliveryType" ItemsSource="{Binding Deliveries}" ItemDisplayBinding="{Binding deliveryFee}" SelectedItem="{Binding DeliverySelectedItem}"
Title="Select a delivery type"
TitleColor="Red">
</Picker>
<Picker x:Name="Picker_ProductType" ItemsSource="{Binding Products}" ItemDisplayBinding="{Binding productPrice}" SelectedItem="{Binding ProductSelectedItem}"
Title="Select a product type"
TitleColor="Red">
</Picker>
<StackLayout Orientation="Horizontal">
<Label Text="Please input quantity: " BackgroundColor="CadetBlue"/>
<Entry Placeholder="0" Text="{Binding Quantity}" TextColor="Red" HorizontalOptions="FillAndExpand"></Entry>
</StackLayout>
<Label x:Name="labelDeliveryFee" Text="{Binding DeliverySelectedItem.deliveryFee,StringFormat='The delivery free is {0:F1}'}" HorizontalOptions="StartAndExpand" BackgroundColor="Yellow"></Label>
<Label x:Name="labelProductPrice" Text="{Binding ProductSelectedItem.productPrice,StringFormat='The product price is {0:F2}'}" HorizontalOptions="StartAndExpand" BackgroundColor="Yellow"></Label>
<StackLayout Orientation="Horizontal">
<Label Text="The total amount: " BackgroundColor="CadetBlue"/>
<Entry Placeholder="0" Text="{Binding TotalAmount}" TextColor="Red" HorizontalOptions="FillAndExpand"></Entry>
</StackLayout>
</StackLayout>
</ContentPage>
Note:
1.I add two objects for the SelectedItem property of two Pickers and implement interface INotifyPropertyChanged for this ViewModel, if we change the value of the property, the UI will update automatically. The same is true for other properties.
private Delivery _deliverySelectedItem;
public Delivery DeliverySelectedItem
{
get => _deliverySelectedItem;
set {
SetProperty(ref _deliverySelectedItem, value);
}
}
public ObservableCollection<Product> Products { get; set; }
//add SelectedItem here
private Product _productSelectedItem;
public Product ProductSelectedItem
{
get => _productSelectedItem;
set {
SetProperty(ref _productSelectedItem, value);
}
}
In this condition, we don't need add event SelectedIndexChanged for Picker.
I get this error in my PartialView when I run my project "An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Unknown Module.
but was not handled in user code
Additional information: System.Web.Mvc.SelectListItem contains no definition for value"
I have two tables category and Product in my databse, using EntityFramework ADO.ENTITY and the project is ASP.NET MVC
In Product table I have ProductId, ProductName and CategoryId
I want to create Cascading from Category DropDownList to Product DropDownList , I mean I want first to chose Category and then all product with the same CategoryId.
But does not working as it is, and please Help me.
This is my Controller:
public class CasController : Controller
{
// GET: Cas
public ActionResult Index()
{
Db db = new Db();
ViewBag.Categories = new SelectList(GetCategoryList(), "CategoryId", "CategoryName");
return View();
}
public List<Category> GetCategoryList()
{
Db db = new Db();
List<Category> categories = db.Category.ToList();
return categories;
}
public ActionResult GetProductList(int catId)
{
using (Db db = new Db())
{
List<Product> prList = db.Product.Where(x => x.CatId == catId).ToList();
ViewBag.ProductOPtions = new SelectList(prList, "ProductId", "ProductName");
return PartialView("DisplayProduct");
}
}
}
And this is my Cascadingclass
public class CasCadingClass
{
public int CatId { get; set; }
public int PrId { get; set; }
}
This is Index view
#model Market.Models.CasCadingClass
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#if (ViewBag.Categories != null)
{
#Html.DropDownListFor(m => m.CatId, ViewBag.Categories as SelectList, "---Select Category---", new { #class = "form-control" })
}
#Html.DropDownListFor(m => m.PrId, new SelectList(""), "--Select Product--", new { #class = "form-control" })
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CatId").change(function () {
var catId = $(this).val();
debugger
$.ajax({
type: "Post",
url: "/Cas/GetProductList?catId=" + catId,
contentType: "html",
success: function (response) {
debugger
$("#PrId").empty();
$("#PrId").append(response);
}
})
})
});
</script>
// Here in PartielView goes error
#model Market.Product
<option value="">--- select Product---</option>
#if (ViewBag.ProductOPtions != null)
{
foreach (var item in ViewBag.ProductOPtions)
{
<option value="#item.value">#item.Text</option>
}
}
This is how we implement cascade drop down for year and month. After selecting year/month the form is submitted. When the View back after Submit, the selected Year value is persist (as we have handling for this in Model), but the selected Month value is not persist. What need to do to persist the value?
Model
public class MyViewModel
{
public int? Year { get; set; }
public int? Month { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable.Range(2000, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
Controller
The HttpGet and HttpPost action,
//
// GET: /MenuSix/
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
public ActionResult Months(int year)
{
if (year == 2011)
{
return Json(
Enumerable.Range(1, 3).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
return Json(
Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
//
// POST: /MenuSix/
[HttpPost]
public ActionResult Index(MyViewModel myViewModel)
{
var month = myViewModel.Month; //11
var year = myViewModel.Year; //2011
return View(myViewModel);
}
View
What need to change here to persist month value "Enumerable.Empty()"?
#model DemoWeb.Models.MenuSix.MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.Year, new SelectList(Model.Years, "Value", "Text"), "-- select year --")
#Html.DropDownListFor(x => x.Month, Enumerable.Empty<SelectListItem>(), "-- select month --")
<div align="center">
<input type="submit" id="valSubmit" value="Save"/>
</div>
}
#section PageScriptsAndCSS{
<script type="text/javascript">
$(document).ready(function () {
$('#Year').change(function () {
debugger;
var selectedYear = $(this).val();
if (selectedYear != null && selectedYear != '') {
$.getJSON('#Url.Action("Months")', { year: selectedYear }, function (months) {
var monthsSelect = $('#Month');
monthsSelect.empty();
$.each(months, function (index, month) {
monthsSelect.append($('<option/>', {
value: month.value,
text: month.text
}));
});
});
}
});
});
</script>
}
Yes, you need to change the way you bind month's dropdown. As, you bind it with an empty list
You would not get the selected month value after form submit. I have changed your code in my way. let me know if it fits to your need.
Model
public class MyViewModel
{
public int? Year { get; set; }
public int? Month { get; set; }
public static IEnumerable<int> GetMonthsRangeOf(int year) {
return (year ==2011) ? Enumerable.Range(1, 3) : Enumerable.Range(1, 12);
}
public IEnumerable<SelectListItem> Years { get {
return Enumerable.Range(2000, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
} }
public IEnumerable<SelectListItem> Months
{
get
{
IEnumerable<SelectListItem> months = null;
if (! this.Year.HasValue)
{
months = Enumerable.Empty<SelectListItem>();
}
else
{
months = GetMonthsRangeOf(this.Year.Value).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
return months;
}
}
}
Controller
public ActionResult Months(int year)
{
return Json(
MyViewModel.GetMonthsRangeOf(year).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
//
// POST: /MenuSix/
[HttpPost]
public ActionResult About(MyViewModel myViewModel)
{
var month = myViewModel.Month; //11
var year = myViewModel.Year; //2011
return View(myViewModel);
}
View
#model TestFreezeMVC.ViewModel.MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(x => x.Year, new SelectList(Model.Years, "Value", "Text"), "-- select year --")
#Html.DropDownListFor(x => x.Month, new SelectList(Model.Months, "Value", "Text"), "-- select month --");
<div align="center">
<input type="submit" id="valSubmit" value="Save"/>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('#Year').change(function () {
var selectedYear = $(this).val();
if (selectedYear != null && selectedYear != '') {
$.getJSON('#Url.Action("Months")', { year: selectedYear }, function (months) {
var monthsSelect = $('#Month');
monthsSelect.empty();
$.each(months, function (index, month) {
monthsSelect.append($('<option/>', {
value: month.value,
text: month.text
}));
});
});
}
});
});
</script>
Suggest if I did something wrong..
Below all my code,
*Model *
Below is Model code,
public class MyViewModel
{
public int? Year { get; set; }
public int? Month { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable.Range(2000, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
Controller
Below is Controller code,
//
// GET: /MenuSix/
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
public ActionResult Months(int year)
{
if (year == 2011)
{
return Json(
Enumerable.Range(1, 3).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
return Json(
Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
JsonRequestBehavior.AllowGet
);
}
View
Below is View code,
#model DemoWeb.Models.MenuSix.MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.Year,
new SelectList(Model.Years, "Value", "Text"),
"-- select year --"
)
#Html.DropDownListFor(
x => x.Month,
Enumerable.Empty<SelectListItem>(),
"-- select month --"
)
}
#section PageScriptsAndCSS{
<script type="text/javascript">
$('#Year').change(function () {
debugger;
var selectedYear = $(this).val();
if (selectedYear != null && selectedYear != '') {
$.getJSON('#Url.Action("Months")', { year: selectedYear },
function (months) {
var monthsSelect = $('#Month');
monthsSelect.empty();
$.each(months, function (index, month) {
monthsSelect.append($('<option/>', {
value: month.value,
text: month.text
}));
});
});
}
});
</script>
}
I'm testing above code, but in jquery code not called here, please suggest why the dropdown change event not called in jquery?
Wrap the javascript code in document.ready to ensure that control is available when binding then event. IT looks this javascript is rendered at the head and at that point drop down is not yet added to the DOM
$(document).ready(function()
{
$("#year").///rest of the code
});
I have model
public class QuestionViewModel
{
public string Text { get; set; }
public int Id { get; set; }
public bool IsMultiSelected { get; set; }
public IEnumerable<RadioButtonViewModel> AnswerViewModels { get; set; }
}
public class RadioButtonViewModel
{
public string Value { get; set; }
public string Name { get; set; }
}
And test controller
[HttpGet]
public ActionResult ProcessAnswers()
{
var question1 = new List<RadioButtonViewModel>
{
new RadioButtonViewModel
{
Value = "1",
Name = "Radio 1 option 1"
},
new RadioButtonViewModel
{
Value = "2",
Name = "Radio 1 option 2"
},
new RadioButtonViewModel
{
Value = "3",
Name = "Radio 1 option 3"
}
};
var question2 = new List<RadioButtonViewModel>
{
new RadioButtonViewModel
{
Value = "1",
Name = "Radio 2 option 1"
},
new RadioButtonViewModel
{
Value = "2",
Name = "Radio 2 option 2"
},
new RadioButtonViewModel
{
Value = "3",
Name = "Radio 2 option 3"
}
};
var qs = new List<QuestionViewModel>
{
new QuestionViewModel
{
Id = 1,
Text = "Please select correct variant in question 1",
AnswerViewModels = question1
},
new QuestionViewModel
{
Id = 2,
Text = "Please select correct variant in question 2",
AnswerViewModels = question2
}
};
return View("TestRadioView", qs);
}
[HttpPost]
public ActionResult ProcessAnswers(List<QuestionViewModel> answers)
{
return RedirectToAction("Index");
}
My View
#using System.Web.Mvc.Html
#using ExpertApplication.ViewModels
#model List<QuestionViewModel>
#{
ViewBag.Title = "Test Radio Button View";
}
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
</head>
<body>
<div>
#if(Model != null)
{
<br />
using(#Html.BeginForm("ProcessAnswers", "Home", FormMethod.Post))
{
foreach(var question in Model)
{
<h2>#question.Text</h2>
<br />
foreach(var radioButtonViewModel in question.AnswerViewModels)
{
#Html.RadioButton(question.Id.ToString(), radioButtonViewModel.Value)
#Html.Label(question.Id.ToString(), radioButtonViewModel.Name)
<br />
}
}
<input type="submit" value="Send" />
}
}
</div>
</body>
</html>
UPDATE
I change my view and model but i don't have correct answers
public IList<RadioButtonViewModel> AnswerViewModels { get; set; }
#using System.Web.Mvc.Html
#using ExpertApplication.ViewModels
#model List<QuestionViewModel>
#{
ViewBag.Title = "Test Radio Button View";
}
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
</head>
<body>
<div>
#if(Model != null)
{
if(ViewData["Message"] != null)
{
<h1>#ViewData["Message"]</h1>
}
else
{
<h1>Please answer the questions</h1>
}
<br />
using(#Html.BeginForm("ProcessAnswers", "Home", FormMethod.Post))
{
for(int i = 0; i < Model.Count(); i++)
{
var question = Model[i];
<h2>#question.Text</h2>
<br />
for(int j = 0; j < question.AnswerViewModels.Count(); j++)
{
var radioButtonViewModel = question.AnswerViewModels[j];
#Html.RadioButton(string.Format("QuestionViewModel[{0}].AnswerViewModels.Id", question.Id), radioButtonViewModel.Value)
#Html.Label(string.Format("{0}", question.Id), radioButtonViewModel.Name)
<br />
}
}
<input type="submit" value="Send" />
}
}
</div>
</body>
</html>
In action ProcessAnswers variable List answers is null.
Where is my trouble ?
The model binder can not create a type of IEnumerable so you will have to change it to a List or Collection