How to Prevent Drop down to show values that is in Database - c#

I want to prevent the value of the dropdown list when it is already in the database file so that theres no multiple input in the Database ,
I hope someone can Help me with this problem ,
I'm using MVC 3 and Kendo UI
is that possible to handle it via Jquery or a Linq Statement in the Controller ?
Thanks :)
<span>
#Html.DropDownList("ddlDay", new SelectList(ViewBag.DayList, "ID", "Display_Value", PersonDay), "[Please Select]",
new Dictionary<string, object>
{
{"class","validate[required] inputLong"}
})
</span>
This Dropdown Show Monday to Sunday , i have 2 of this drop down that shows availability But i like to know that if i save Monday to Wednesday , Monday to Wednesday is removed on the two dropdowns ,
private void GetDayList()
{
var dayList = (from a in db.Lookups
where a.Domain == "DAYSTATUS"
select a).ToList();
ViewBag.DayList = dayList ;
}

You can solve this in many ways, it will depend on how your interaction is done.
You could use LINQ, adding a Where() or Except() statement to filter the full list:
var fromDayList = dayList.Where(day => day.Name != selectedFromDay).ToList();
// or if multiple selected days, assuming it is of the same type:
var validDayList = dayList.Except(selectedDayList).ToList();
If you allow them to change the selected days client side and are using AJAX (which is how you usually use Kendo UI) then you won't want to filter server side. Instead you should wrap your DayList in a kendo.DataSource and apply a filter based on selected days in your JavaScript. You haven't provided enough information for me to supply any sample code for this.

Related

How to validate every value in a List in where Clause?

The Title is a little bit complicating.
The Question here is easy:
If got a CheckBoxList. In this List you are allowed to do multiple choice. I put every chosen value from the Checkboxlist into a list because i need it for my where clause. So i have:
List<int> queueIDList = new List<int>();
Short version of my LINQ:
var reports = from t in tickets
where t.queue_id == every value in queueIDList
select t.ticketnumber;
So how do i have to write it when i want every ticketnumber from DB which is the same like in the queueIDList?
For better knowing - in the CheckBoxList u can chose different Queues, at least u have to chose 1 (null is not allowed). I added the ID's of the chosen Queues to a list and now i want to have every ticketnumber from DB where the queueID equals with the values from the queueIDList.
I think the answer is easy but i'm really stuck with my mind.
Thanks for every help!
You can just use Contains:
var reports = from t in tickets
where queueIDList.Contains(t.queue_id)
select t.ticketnumber;

Query Expression Distinct column Dynamics CRM 2011

I have created a query expressions which retrieves all order products associated with an order.
Here is my current query expression:
var query = new QueryExpression("salesorderdetail");
query.ColumnSet = new ColumnSet(new string[] { "salesorderdetailid", "productid", "new_event", "new_inventory", "productdescription" });
query.Criteria.AddCondition("salesorderid", ConditionOperator.Equal, combinedEntity.Id);
query.Distinct = true;
EntityCollection retrieved = context.OrganizationService.RetrieveMultiple(query);
The problem is that I only want to retrieve data with a unique productid.
Is this possible using QueryExpression? Can anyone show me?
Many thanks.
I am not 100% sure what you are asking, however there is a trick I like to use that may help when writing query expressions:
Navigate to the view that displays the records in question
Click the Advanced Find button in the Ribbon Bar
Configure your “find” until it shows the records you are looking for
Click the Download Fetch XML button in the Ribbon Bar
Open the file with a text viewer (or your fav dev tool)
While this is not “code” per se, it usually contains some good hints on how to write it. Also, there is the option of using a Fetch XML query in your code as well.
Use FetchXML to Construct a Query
http://msdn.microsoft.com/en-us/library/gg328117.aspx
If you just need the distinct set of ProductIds contained within the sales order, couldn't just remove the other columns from the ColumnSet? Like so:
query.ColumnSet = new ColumnSet(new string[] { "productid" });

Asynchronous updating list of options for multi select MVC

I'm working on a form for user input, and one of the items (a multiple option select) has an inordinate amount of choices (~1600), so it's gotta get filtered down to be digestible. I've got 3 filter fields (dropdowns) that I'm requiring to have completed before I make an AJAX call back to the DB and get an updated list. It's similar to How to filter the options of a drop down list using another drop down list, however I also don't want to lose any items that were previously selected. Here's the signature for the function I've prototyped:
public JsonResult GetContentStandardsForUser(string type, string grade, string subject, List<SelectListItem> selected)
What I want is to return the new list of items (and not lose the ones that were already selected), and have the pick-list update.
What is this AJAX call going to look like (using jquery)? Should I just include the current selected values in my query, or can I pass the SelectListItems like I've written above?
After some thought about the fantasy football example I presented, I came up with a solution. I make two multi-selects, one of available, one of selected. Only the "selected" list gets bound to the model-- the available list is what gets updated as a result of the query.
If someone can come up with a single-select control solution, I'm still interested, but this is a good workaround for me, for now. The reason I was looking for a single-select solution was that I was already using this plugin (http://www.virtuosoft.eu/code/bootstrap-duallistbox/) to filter my selected/available lists.
ETA: I realized I can do this in a single listbox with jquery. Using the ID, loop through the options, if it's not selected, remove it. Then add all new options from the query. Voila!
ETA2: Now with code!
//Filter content standards
$("#csType, #csGrade, #csSubject").change(function(){
var type = $("#csType").val();
var grade = $("#csGrade").val();
var subject = $("#csSubject").val();
if(type != "" && grade != "" && subject != "")
{
$("#csList option:not(:selected)").remove();
var items="";
$.getJSON("#Url.Action("GetContentStandardsForUser","Summary")", {type:type, grade:grade, subject:subject} ,function (data) {
$.each(data,function(index,item){
items+="<option value='"+item.Value+"'>"+item.Text+"</option>"
});
$("#csList").append(items)
$("#csList").trigger('bootstrapduallistbox.refresh', true);
});
}
});
After binding the options, call following function.
$('#csList').multiselect('rebuild');

Auto-populating Select Boxes using jQuery & AJAX in asp.net MVC

1-problem: I need to enable users to select one or more things from a large amount of information that is grouped into a hierarchical structure for selection, data entry, were data could have a depth of 4, 5 parent categories.
2-functionality I´m looking for:
Similar to eBay shows cascading lists when selecting an item’s category. When the page is displayed, you only get the first list box. After selecting one in the first, the second is displayed. The process continues until the selected category does not have sub-categories.
}
3-actual table and query:
table:
-int Id
-string Name
-int ParentId
query:
public IList<CategoryTable> listcategories(int parentId)
{
var query = from c in categorytable
where c.ParentId == parentId
select c;
var result= query.ToList();
return result;
}
4-I dont know how to start, any guideline, live example jsfiddle, demo or tutorial would be greatly appreciated.
brgds
UPDATE: I believe that this functionality is not very developed in webtutorials and questions. consequently I started a bounty for a great answer. I will asign the bounty for a live example of the functionality previous commented. thanks!
What I have learned by handling large amounts of data is:
don't try to load all data at once to the client
load only the data the client actually needs
do the filtering, searching and sorting in the database, e.g. by stored procedures. Especially for data, which are distributed across multiple tables.
optimize your database queries, indexes are good
keep always in mind how many simultanious queries do you expect
linq is good but not for everything when handling large data
spend time to think and plan what data are really needed
To display the data on your webpage there many jQuery plugins to list data where you could bind functions to an "selected"-event. For example knockOut.js, which comes with MVC4. You may don't need a fully loaded jQuery "hierachical-data-list-display"-plugin. Perhaps you can realize it by using "seleted"-events, ajax loading and show/hide functions.
According to your comments I would think of a combination of jQuery and MVC:
in MVC I would create a patial view like
#model MvcApplication.Models.DataModel
<ol id="#Model.DataCategorieLevel">
#for (var i = 0; Model.Data.Count > i; i++)
{
<li value="#Model.Data[i].ItemId" onclick="itemSelected(#Model.Data[i].ItemId, #Model.DataCategoryLevel);" >#Model.Data[i].ItemName</li>
}
</ol>
the javascript could be something like:
function itemSelected(selectedItemId, itemCategoryLevel) {
// ajax call to an action which loads the next categorie items into the partial view and returns them
// on success remove all lists with an category - level lower than itemCategoryLevel
// append the returned List to the HTML-container which holds the lists
}
in the called MVC-Action I would determine if it is the last category level or not. If it is the last level, I would return a different partial view with other onclick event bindings
This is what I would try to realize, before I start searching for some plugins
I'm using knockout and Webapi to power cascading dropdowns in an app I'm developing at the moment.
View
I've got a basic dropdown list like below.
<select data-bind="options: CurrentList,
optionsText: 'name',
value: CurrentListSelectedItem,
optionsCaption: 'Please Select...'"></select>
View Model
self.CurrentList = ko.observableArray(CurrentListData);
self.CurrentListSelectedItem = ko.observable();
self.CurrentListSelectedItem.subscribe(function () {
//ajaxcall to populate list 2
});
Server side I've got a simple rest service that take an Id of a point in the tree and returns all its children, this way you can just chain as many of these dropdowns together as you wish (as long as your hierarchy has the levels to match.
See fiddle of working example with mocked data http://jsfiddle.net/tgriley1/vEBGS/
I recently had a similar problem when using Cascading Drop-downs and I did something like this.
Firstly, write some jquery on the view so that when you select the first item it sends an ajax request to the server, and brings back a JSON or xml response.
I did something like
<script>
$(function () {
$("select#ParentId").change(function (evt) {
$.ajax({
url: "/Home/GetChildItems",
type: 'Post',
data: { ParentId: $("select#ParentId").val() },
success: function (data) {
var items = "";
$.each(data, function (i, val) {
items += "<option value='" + val.ChildId + "'>" + val.ChildName + "</option>";
});
$("select#ChildDropDown").empty().html(items);
}
});
});
});
</script>
On the Controller, something like
Public JsonResult GetChildItems(int ParentId)
{
//code to retrieve the data
JsonResult result = new JsonResult();
result.Data = **object that contains the child data**;
return result;
}
I'm a beginner myself, so I'm not sure how good this code is, but it worked for me when creating cascading drop-downs using jquery.
Hope it helps.
Link to the cascading drop down question : Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON
Hi I had the same scenario , What I used is, a autocomplete list with with web API, after specific number of characters , it calls the Web API and loads the data for the particular wild card.
Apart from this when I found that data returned is still large , I added pagination at SQL server end
The telerik demo is always a good place to learn MVC from
http://demos.telerik.com/aspnet-mvc/razor/combobox/cascadingcombobox
This does not exactly use listboxes as per your screenshots but it could very easily be changed to use them. With a few javascript modifications you could have unlimited levels.
Here is another one:
http://weblogs.asp.net/raduenuca/archive/2011/04/03/asp-net-mvc-cascading-dropdown-lists-tutorial-part-5-1-cascading-using-jquery-ajax-ajax-and-dom-objects.aspx

How to populate an AutoCompleteBox filter with distinct values from one property?

My table has a Date field, from which I would like to query all distinct years, and use those years in my ACB screen filter for that same table.
I am trying to figure out the Linq code I need for this. I just need the query to return something like:
2012
2011
2010
and use these values as the Choice List for my Auto Complete Box.
Many thanks.
If your Date field never contains null, this query will do on EF:
var years = (from row in ctx.YourTable
select row.DateField.Year).Distinct().AsEnumerable().Select(e => e.ToString());
This returns an IEnumerable< string > but add .ToList() or ToArray() at the end if it suits to you.
And for the completness, if your Date field is nullable, you should filter out null values:
var years = (from row in ctx.YourTable
where row.DateField != null
select row.DateField.Value.Year).Distinct().AsEnumerable().Select(e => e.ToString());
The only way that you can do what you want is by creating a custom RIA service, then adding it as a data source. It may seems daunting the first time, but it's really very easy.
This link will explain the basics. then you can use the LINQ syntax that Kyle showed in his answer.
How Do I: Display a Chart Built On Aggregated Data
You can't programmatically set the Choice List of an AutoCompleteBox. See this SO question.
However you can use LINQ in the _PreprocessQuery method. Create an empty query using Query Designer, click the down arrow next to "Write Code" and choose the _PreprocessQuery method. Then use #xeondev's LINQ code like this:
partial void Query1_PreprocessQuery(ref IQueryable<TableName> query)
{
query = (from row in query
where row.DateField != null
select row.DateField.Value.Year).Distinct().AsEnumerable().Select(e => e.ToString());
}

Categories

Resources