How simplify my request code? - c#

I use this part of code to get informations from my database, using Entity Framework, and add all of it in a IEnumerable property for, at the end, a DropDownListFor display.
I need to use that kind a code many time so I would like to make it the most powerfull at the begenning.
public IEnumerable<SelectListItem> Functions { get
{
List<SelectListItem> result = new List<SelectListItem>();
using (followupconsultantEntities dataModel = new followupconsultantEntities())
{
var myEvents = from e in dataModel.functions
select e;
foreach (var function in myEvents)
{
SelectListItem myList = new SelectListItem
{
Value = function.ID_Function.ToString(CultureInfo.InvariantCulture),
Text = function.FU_Name
};
result.Add(myList);
}
}
return result;
} }
Thanks for help
The view:
<div class="editor-field">
<%: Html.DropDownListFor(m => m.SelectedFunction,Model.Functions) %>
</div>
For information, my controller:
public ActionResult Register()
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View(new RegisterModel());
}

Start using System.Web.Mvc.SelectList.
public IEnumerable<SelectListItem> Functions { get
{
using (followupconsultantEntities dataModel = new followupconsultantEntities())
{
return new SelectList(dataModel.functions.ToArray(), "ID_Function", "FU_Name");
}
}
Also consider AutoMapper.

Try this. In this code you will not get from database data that you not need.
public IEnumerable<SelectListItem> Functions { get
{
using (followupconsultantEntities dataModel = new followupconsultantEntities())
{
return new SelectList(dataModel.functions.Select(f=>
new
{
Value = function.ID_Function.ToString(CultureInfo.InvariantCulture),
Text = function.FU_Name
})
.ToArray(), "Value", "Text");
}
}

Related

How to bind list of string in kendo dropdownlist

Hello I am using Kendo for ASP.NET MVC.
I have list of string containing data
[0]="str1"
[1]="str2"... and so on
Now I want to bind this list of string into kendo dropdownlist.
I have bind dropdownlist by list of class with name and id but with only one data in list of string, I don't know how to bind that!
I have done that like below:
#(
Html.Kendo().DropDownList()
.Name("ddlstrings")
.DataTextField("stringname")
.DataValueField("stringname")
//.Events(x => x.Select("sourceclick"))
.SelectedIndex(0)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getData", "String");
});
})
)
But I got undefined.
I am returning the data like this:
public JsonResult getData()
{
try
{
List<string> stringlist = object.getstrlist();
return Json(stringlist, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json("", JsonRequestBehavior.AllowGet);
}
}
Does anyone have any idea how can I do this!
Any help would be appreciate.
Don't know is it good or not but got the solution with some manual work:
var selectList = new List<SelectListItem>();
foreach (var element in stringlist)
{
selectList.Add(new SelectListItem
{
Value = element.ToString(),
Text = element.ToString()
});
}
return Json(selectList, JsonRequestBehavior.AllowGet);
and at view side:
#(
Html.Kendo().DropDownList()
.Name("ddlstrings")
.DataTextField("Text")
.DataValueField("Value")
//.Events(x => x.Select("sourceclick"))
.SelectedIndex(0)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getData", "String");
});
})
)
The answer you have provided is right actually. The Action must return List<SelectListItem> as the output. See this Example and in the code see the BindTo property.
You can just update your code to below.
public JsonResult getData()
{
try
{
var stringlist = object.getstrlist().select( x=> new SelectListItem
{
Value = x,
Text = x
}).ToList();
return Json(stringlist, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json("", JsonRequestBehavior.AllowGet);
}
}
I have just modified your code to not have a for loop.
Try ValuePrimitive:
Html.Kendo().DropDownList()
.Name("ddlstrings")
.ValuePrimitive(true)
.SelectedIndex(0)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getData", "String");
});
})
What does your getData() return? You need to return an enumerable of object that have a property called stringname or what ever property name you specify in the DataText/DataValue fileds.
Something like this:
return Json(youStringArray.Select(x=>new{stringname = x}))
using TestSolution.Utility;
...
public JsonResult getData()
{
try
{
var stringlist = object.getstrlist();
return Json(stringlist.ToIdNameList(), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json("", JsonRequestBehavior.AllowGet);
}
}
=============================
using TestSolution.Models;
using System.Collections.Generic;
using System.Linq;
namespace TestSolution.Utility
{
/// <summary>
/// Kendo Drop Down List Extention
/// </summary>
public static class KendoDropDownListExtention
{
public static List<IdName> ToIdNameList(this string[] stringList)
{
return stringList.Select(sl => new IdName() { Name = sl, Value = sl }).ToList();
}
}
}

How can I capture the #Html.DropDownListFor selected value?

I am using MVC5, Razor, Entity Framework, C#. I am trying to pass a value of a dorpdown list using a link.
my model is
public class TestVM
{
public string TheID { get; set; }
}
I am loading an enum into a IEnumerable<SelectListItem>.
My enum is
public enum DiscountENUM
{
SaleCustomer,
SaleCustomerCategory,
SaleProduct,
SaleProductCategory,
SaleCustomerAndProduct,
SaleCustomerAndProductCategory,
SaleCustomerCategoryAndProductCategory,
PurchaseVendor,
PurchaseVendorAndProduct,
PurchaseVendorAndProductCategory,
PurchaseProduct,
PurchaseProductCategory,
Unknown
}
I am using the index method of the home controller
public ActionResult Index()
{
ViewBag.ListOfDiscounts = SelectListDiscountENUM();
TestVM d = new TestVM();
return View(d);
}
Where I load the ListOfDiscounts using:
private IEnumerable<SelectListItem> SelectListDiscountENUM()
{
List<SelectListItem> selectList = new List<SelectListItem>();
var listOfEnumValues = Enum.GetValues(typeof(DiscountENUM));
if (listOfEnumValues != null)
if (listOfEnumValues.Length > 0)
{
foreach (var item in listOfEnumValues)
{
SelectListItem sVM = new SelectListItem();
sVM.Value = item.ToString();
sVM.Text = Enum.GetName(typeof(DiscountENUM), item).ToString();
selectList.Add(sVM);
}
}
return selectList.OrderBy(x => x.Text).AsEnumerable();
}
My create method which is called from the view is
public ActionResult Create(TestVM d, string TheID)
{
return View();
}
My Index view is
#model ModelsClassLibrary.Models.DiscountNS.TestVM
<div>#Html.ActionLink("Create New", "Create", new { TheID = Model.TheID})</div>
<div>
#Html.DropDownListFor(x => x.TheID, #ViewBag.ListOfDiscounts as IEnumerable<SelectListItem>, "--- Select Discount Type ---", new { #class = "form-control" })
</div>
The problem is in the following line in the View
<div>#Html.ActionLink("Create New", "Create", new { TheID = Model.TheID })</div>
I have tried adding a model with the name of the field as "TheID"... no luck. Also, added a string field in the parameter, no luck. I looked at the FormControl object, and there was nothing in it either! I suspect something has to be added at the Route level in the helper, but I don't know what.
Model.TheID is always null. Even when I select an item in the DropDownListFor.
Does anyone have an idea how I can capture the select value of the DropDownListFor and send it into the Html.ActionLink TheID?

Set selected index of dropdown to zero after form submit in ASP.NET MVC

I am bit to new asp.net mvc and using aps.net mvc 5. I have create the below dropdown using html helpers in aps.net mvc. When i submit(post back) the form i want to set the selected index to zero. Here i am using a optionLabel "--select--". I want to set the selected value to that one ("--select--") after post back. How to achieve this. Please help. Thank you.
#Html.DropDownListFor(model => model.TestCategory, new SelectList(#ViewBag.TestCategories, "value", "text"), "-- Select --", new { #class = "form-control input-sm"})
Controller Code
[HttpGet]
public ActionResult Index()
{
var model = new LaboratoryViewModel {
medicaltestlist = new List<MedicalTest>()
};
PopTestCategory();
PopEmptyDropdown();
return View(model);
}
[HttpPost]
public ActionResult Index(LaboratoryViewModel labvm)
{
var test = PopMedicalTests().Where(x => x.TestSerial == Convert.ToInt32(labvm.TestCode)).FirstOrDefault();
if (labvm.medicaltestlist == null)
labvm.medicaltestlist = new List<MedicalTest>();
if(!labvm.medicaltestlist.Any(x=> x.TestSerial == test.TestSerial))
labvm.medicaltestlist.Add(test);
labvm.TestCategory = "";
PopTestCategory();
return View(labvm);
}
public void PopTestCategory()
{
var categorylist = new List<DropDownItem>
{
new DropDownItem{value="Medical",text="Medical"},
new DropDownItem{value="Animal",text="Animal"},
new DropDownItem{value="Food",text="Food"},
new DropDownItem{value="Water",text="Water"}
};
ViewBag.TestCategories = categorylist;
}
public class DropDownItem
{
public int id { get; set; }
public string value { get; set; }
public string text { get; set; }
}
You return the view in you post method so if you selected (say) Animal then that value will be selected when you return the view because the html helpers use the values from ModelState, not the model property. Setting labvm.TestCategory = ""; has no effect. The correct approach is to follow the PRG pattern and redirect to the GET method, however you can make this work by calling ModelState.Clear(); before setting resetting the value of TestCategory although this will clear all ModelState properties and errors and may have other side effects.
Side note: You DropDownItem class seems unnecessary. MVC already has a SelectListItem class designed to work with dropdownlists, and in any case you can replace all the code in your PopEmptyDropdown() method with
ViewBag.TestCategories = new SelectList(new List<string>() { "Medical", "Animal", "Food", "Water" });
and in the view
#Html.DropDownListFor(m => m.TestCategory, (SelectList)#ViewBag.TestCategories, "-- Select --", new { #class = "form-control input-sm"})
If you set the "value" attribute of the top item in the drop down list to something and then pass back a model containing that for the bound property it should work?

Razor looping through Viewbag and bind to it

I have list of objects in my coming from controller.
it looks like this
{ Driver = System.Data.Entity.Driver_Driver1, Statuss = NotConfirmed }
{ Driver = System.Data.Entity.Driver_Driver2, Statuss = NotConfirmed }
please note that Driver is a complex type object.
Controller:
var Drivers = _db.Drivers.Where(x => x.DriverCompanyID == id).Where(d => d.CanWorkIn.Where(f => f.CompanyToDriveFor.CompanyID == OwnCompany.CompanyID).Any())
.Select(x => new
{
Driver = x,
Statuss = x.CanWorkIn.FirstOrDefault().Status.ToString()
}).ToList();
ViewBag.ListOfDrivers = Drivers;
return PartialView("_DriverList");
My Model
public class DriverViewItem
{
public Driver Driver { get; set; }
public string Statuss { get; set; }
}
My View
#model List<MyApp.web.Models.DriverViewItem>
and this last bit does not work. model declaration.
First create a strongly typed class with the properties you require. I've called mine DriverViewItem.
Then in your controller change the select to select this DriverViewItem and parse the list as a model to the view.
var Drivers = _db.Drivers.Where(x => x.DriverCompanyID == id).Where(d => d.CanWorkIn.Where(f => f.CompanyToDriveFor.CompanyID == OwnCompany.CompanyID).Any())
.Select(x => new DriverViewItem()
{
Driver = x,
Statuss = x.CanWorkIn.FirstOrDefault().Status
}).ToList();
return PartialView("_DriverList", Drivers);
In the view you will need to tell the view to expect your model you can do this with:
#model List<DriverViewItem>
Then you can iterate through the items like so:
#foreach(DriverViewItem item in Model)
{
<div>
<p>#item.Driver.{what ever property}</p>
<p>#item.Statuss</p>
</div>
}
This is a much cleaner way than parsing data using the ViewBag.
It would be better to use the model instead to pass this kind of data. But to answer the question directly, in the controller, assign it as an array of items to the viewbag
ViewBag.Data = {
new { Driver = System.Data.Entity.Driver_Driver1, Status = NotConfirmed },
new { Driver = System.Data.Entity.Driver_Driver2, Status = NotConfirmed }
}
And in the markup:
#{
if (ViewBag.Data != null){
foreach (var item in ViewBag.Data) {
//show the item in the view
}
}
}

How Do I Model Bind A List Of 'List<SelectItem>' Using MVC.Net

I am trying to create a form that will consist of a series of dropdown lists, all of which are loaded from a database. I will not know how many dropdown lists will be needed, or how many options each dropdown list will have at compile-time.
How can these fields be set-up to allow them to model-bind when posted?
There is a lot of other complexity in each of the below code elements, but I cannot get the model binding to work even when reduced down to a basic level.
The Models:
public class MyPageViewModel
{
public List<MyDropDownListModel> ListOfDropDownLists { get; set; }
}
public class MyDropDownListModel
{
public string Key { get; set; }
public string Value { get; set; }
public List<SelectListItem> Options { get; set; }
}
The Controller Get Action:
[AcceptVerbs(HttpVerbs.Get)]
[ActionName("MyAction")]
public ActionResult MyGetAction()
{
var values_1 = new List<string> {"Val1", "Val2", "Val3"};
var options_1 =
values_1
.ConvertAll(x => new SelectListItem{Text=x,Value=x});
var myDropDownListModel_1 =
new MyDropDownListModel { Key = "Key_1", Options = options_1 };
var values_2 = new List<string> {"Val4", "Val5", "Val6"};
var options_2 =
values_2
.ConvertAll(x => new SelectListItem{Text=x,Value=x})};
var myDropDownListModel_2 =
new MyDropDownListModel { Key = "Key_2", Options = options_2 };
var model =
new MyPageViewModel
{
ListOfDropDownLists =
new List<MyDropDownListModel>
{
myDropDownListModel_1,
myDropDownListModel_2,
}
};
return View(model);
}
The Controller Post Action:
[AcceptVerbs(HttpVerbs.Post)]
[ActionName("MyAction")]
public ActionResult MyPostAction(MyPageViewModel model)
{
//Do something with posted model...
//Except 'model.ListOfDropDownLists' is always null
return View(model);
}
The View:
#model MyPageViewModel
#using (Html.BeginForm("MyPostAction"))
{
foreach (var ddl in Model.ListOfDropDownLists)
{
#Html.DropDownListFor(x => ddl.Value, ddl.Options)
}
<button type="submit">Submit</button>
}
Edit: Corrected typos and copy-paste mistakes.
Solution:
The problem turned out to be the foreach-loop within the view. Changing it into a for-loop instead caused the post to populate as expected. The updated view is below:
#using (Html.BeginForm("MyPostAction"))
{
for (int i = 0; i < Model.ListOfDropDownLists.Count; i++)
{
#Html.HiddenFor(x => x.ListOfDropDownLists[i].Key)
#Html.DropDownListFor(m => m.ListOfDropDownLists[i].Value, Model.ListOfDropDownLists[i].Options);
}
<button type="submit">Submit</button>
}
Your view is only creating multiple select elements named dll.Value (and duplicate ID's) which has no relationship to your model. What you need is to create elements named ListOfDropDownLists[0].Value, ListOfDropDownLists[1].Value etc.
Change you loop in the view to this
for (int i = 0; i < Model.ListOfDropDownLists.Count; i++)
{
#Html.DropDownListFor(m => m.ListOfDropDownLists[i].Value, Model.ListOfDropDownLists[i].Options);
}
You posted code has multiple errors (e.g. your pass a model of type MyPageViewModel but the post action method expects type of MyModel). I assume these are just typo's.
I can give you my solution,It is working:
Method in base controller
//To bind Dropdown list
protected Dictionary<int, string> GenerateDictionaryForDropDown(DataTable dtSource, string keyColumnName, string valueColumnName)
{
return dtSource.AsEnumerable()
.ToDictionary<DataRow, int, string>(row => row.Field<int>(keyColumnName),
row => row.Field<string>(valueColumnName));
}
Code in controller:
DataTable dtList = new DataTable();
dtList = location.GetDistrict();
Dictionary<int, string> DistrictDictionary = GenerateDictionaryForDropDown(dtList, "Id", "DistrictName");
model.DistrictList = DistrictDictionary;
Binding Data in view:
#Html.DropDownListFor(model => model.DiscrictId, new SelectList(Model.DistrictList, "Key", "Value"), new { id = "ddlDist", #class = "form-control" })
Binding Other Dropdown from this(cascading):
Other Dropdown:
#Html.DropDownListFor(model => model.TalukaId, new SelectList(Model.TalukaList, "Key", "Value"), new { id = "ddlTaluka", #class = "form-control" })
JQuery Code:
$("#ddlDist").change(function () {
var TalukaList = "Select"
$('#ddlTaluka').html(TalukaList);
$.ajax({
type: "Post",
dataType: 'json',
url: 'GetTaluka',
data: { "DistId": $('#ddlDist').val() },
async: false,
success: function (data) {
$.each(data, function (index, optionData) {
TalukaList = TalukaList + "<option value='" + optionData.Key + "'>" + optionData.Value + "</option>";
});
},
error: function (xhr, status, error) {
//alert(error);
}
});
$('#ddlTaluka').html(TalukaList);
});
Controller Method Return JSON
public JsonResult GetTaluka(int DistId)
{
LocationDH location = new LocationDH();
DataTable dtTaluka = location.GetTaluka(DistId);
Dictionary<int, string> DictionaryTaluka = GenerateDictionaryForDropDown(dtTaluka, "ID", "TalukaName");
return Json(DictionaryTaluka.ToList(), JsonRequestBehavior.AllowGet);
}

Categories

Resources