I am working on an ASP.NET MVC application using Syncfusion controls. I have a drop down list in my view. The model has a property "Categories" which is a List of type Category.
public class Category
{
public int XKategorieId { get; set; }
public int? Id { get; set; }
public string Hinweis { get; set; }
public string Kategorie { get; set; }
}
The model of the view also has a property "IdFromCategory". The model is:
public class ReportModel
{
public int? IdFromCategory { get; set; }
public List<Category> Categories { get; set; }
}
I am showing all the categories in the drop down list by setting the "DataSource" of "DropDownList". Now, my issue is that i want to show an item selected in the "DropDownList" when the view loads and that selected item will be the one with "Id" equals to "IdFromCategory ".
#Html.EJS().DropDownList("KundenBetreuung").DataSource(Model.Categories).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Text = "Kategorie", Value = "Id" }).Value(Model.IdFromCategory.ToString()).Width("100%").Render();
This is my code, i am unable to set the selected item in the "DropDownList"
In the Razor code, you have filled the value property with Model.IdFromCategory.ToString() (a string) where the declared properties IdFromCategory and Id both are integers. This mismatching type is the cause of the issue in your end and the value is not being set. To successfully set the value make sure that the value provided is available in the datasource and its type matches as well.
Suggest changing the code as follows
#Html.EJS().DropDownList("KundenBetreuung").DataSource(Model.Categories).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Text = "Kategorie", Value = "Id" }).Value(Model.IdFromCategory).Width("100%").Render();
Check the following example for further reference
Example
Related
I have the same set up of databindings as this one
Visual Studio Winform designer: Set DataBindings on current control BindingSource
But I don't know how to change the value of let's say I have 2 models:
class Receipt {
public int ProductId { get; set; }
public double Price { get; set; }
//etc...
}
class Product {
public int ProductId { get; set; }
public string ProductName { get; set; }
//etc...
}
My datagrid shows the Receipt model and when one is selected, my textboxes shows other details which are not displayed in the datagrid.
Now my problem is I need to display on my text box the ProductName instead of the ProductId.
I am using Entity Framework Code First.
Please help...
TIA.
Since you are using Entity Framework and you have Product property in Receipt class, you can load Product with Receipt, for example this way:
this.receiptBindingSource.DataSource = db.Receipt.Include("Product").ToList();
You can set the databinding of your TextBox to bind to Product.ProductName property using the designer or code:
this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text",
this.receiptBindingSource, "Product.ProductName", true));
I'm not sure what I'm doing wrong. I have a model with a SelectList property that will contain multiple dates as its values. I want to display these values without the timestamp added. How can I show these dates in shortdatetime format? I have the following ViewModel:
public class EditWeightsViewModel
{
[DisplayName("Associates")]
public SelectList AssociatesList { get; set; }
[DisplayName("Week")]
public SelectList WeeksOfEntryList { get; set; }
public decimal Weight { get; set; }
}
Here's part of my controller (*Note, weeks is a List of DateTimes):
editWeightsViewModel.WeeksOfEntryList = new SelectList(weeks.Select(item => new SelectListItem
{
Selected = false,
Value = item.ToString(),
Text = item.ToShortDateString()
}));
My dropdownlist is showing System.Web.MVC.SelectListItem instead of the actual dates. What am I doing wrong? Am I wrong to go about it this way? Would it be easier to create an editor template that displays this in ShortDateTime format?
Html.DropDownListFor helper method's second argument is a collection of SelectListItem. So change the type of WeeksOfEntryList property to a list of SelectListItem. I also added another property, SelectedWeek to store the selected option value.
public class EditWeightsViewModel
{
public string SelectedWeek {set;get;}
[DisplayName("Week")]
public List<SelectListItem> WeeksOfEntryList { get; set; }
[DisplayName("Associates")]
public SelectList AssociatesList { get; set; }
public decimal Weight { get; set; }
}
And when you load the WeeksOfEntryList property value of your viewmodel.
public ActionResult Create()
{
var vm = new EditWeightsViewModel();
vm.WeeksOfEntryList = weeks.Select(s=> new SelectListItem
{ Value=s.ToShortDateString(),
Text=s.ToShortDateString()}).ToList();
//If you want to keep one option selected, Set the vm.SelectedWeek property value.
return View(vm);
}
And in your razor view,
#using YourNameSpaceHere.EditWeightsViewModel
#Html.DropDownListFor(s=>s.SelectedWeek, Model.WeeksOfEntryList ,"Select")
I have a radcombobox and I'm trying to bind the selected value to data I'm pulling back from a table in my database.
<telerik:RadComboBox ID="cboRole" runat="server" DataValueField="UserType.ID" DataTextField="UserType.Value" Text='<%# Bind("UserType") %>' DataSourceID="odsCertifications" >
</telerik:RadComboBox>
Here is my data
public partial class Certification
{
public Certification()
{
this.Courses = new HashSet<CertificationCourse>();
}
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Duration { get; set; }
public Nullable<System.DateTime> Expiration { get; set; }
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public System.DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedOn { get; set; }
public Nullable<int> UserTypeID { get; set; }
public virtual ICollection<CertificationCourse> Courses { get; set; }
public virtual SystemCode UserType { get; set; }
}
The UserType has the attributes Value and ID upon which I'm trying to bind the DataTextFields and DataValueFields. However, I'm getting javascript exceptions when trying to bind this way. The javascript message if omitted so I can't fully see what the exact error message is.
Here is what the chrome js debugger is telling me is happening:
Uncaught Sys.WebForms.PageRequestManagerServerErrorException:
Sys.WebForms.PageRequestManagerServerErrorException: Object of type
System.Data.Entity.DynamicProxies.Certification_D985D293565CB0BFD87FA8F8F44D70ACF4130D6E138A82D6E486544C53D7FE10 does ...<omitted>...y.
<asp:ObjectDataSource runat="server" ID="odsCertifications" SelectMethod="GetActiveCertifications" TypeName="SitefinityWebApp.Controllers.CertificationController"></asp:ObjectDataSource>
public List<Certification> GetActiveCertifications()
{
using (var db = new Entities())
{
try
{
return db.Certifications.Include("UserType").Where(x => x.IsActive == true).OrderBy(x => x.Title).ToList();
}
catch (Exception ex)
{
ExceptionManager.LogException(this, ex);
return null;
}
}
}
I don't have any knowledge in the RAD version of Telerik, but I think the problem comes from the fact that you are trying to bind a SystemCode object to the ComboBox, and it can only probably handles simple types like int / string.
I guess you should be binding with the UserTypeID instead, but I'm not sure it would work because it's Nullable.
What would you like to do exactly? I guess "odsCertifications" is not a list. So if you would like to show only binded user type value which is in certification object. You don't need to bind any source to combobox. Just add list item to combobox in cs. side like:
cbcRole.Items.Add(new RadComboboxItem(){Value=odsCertifications.UserType.ID, Text=odsCertifications.UserType.Value}) //RadComboboxItem and properties can be different I wrote only as example.
If you would like to populate your combobox with all user types and show binded user type value which is in certification object as selected item, You have to bind UserType list object to your combobox like:
<telerik:RadComboBox ID="cboRole" runat="server" DataValueField="ID" DataTextField="Value" DataSourceID="userTypes" ></telerik:RadComboBox>
DataSourceID="userTypes" here, userTypes is must be List object like
List<UserType> userTypes;
Than you can set selected item in cs. side like:
cboRole.SelectedValue=odsCertifications.UserType.ID;
To get the actual server exception, remove AJAX. What you get is a server exception captured by MS AJAX during a partial postback and send (truncated) to the client as a JavaScript error.
I also think you may need to expose the string property you need as a direct field, not as a sub-field of the field you pass to the combo's property
I want to make public property that gets and sets object I get from datagrid.
I have datagrid that has 3 columns with text and 3 columns with checkboxes.
When I check one of the checkbox I get a value of whole row in list like this:
var selectedItemsController = MyObsCollection.Where(n => n.Controller).ToList();
That is a list of objects with all 3 string values (and all 3 bool values of checkboxes) that are in same row where checkboxes in column named Controller is.
MyObsCollection is also public property for ObservableCollection and they are defined like this:
ObservableCollection<RowData> _obsCollection =
new ObservableCollection<RowData>();
public ObservableCollection<RowData> MyObsCollection
{
get { return _obsCollection; }
}
RowData is my class that caries a model I need and it's defined like this:
public class RowData : INotifyPropertyChanged
{
public string Type { get; set; }
public string MapTo { get; set; }
public string Name { get; set; }
public bool Controller { get; set; }
public bool Service { get; set; }
public bool Injection { get; set; }
public RowData(string type, string mapTo, string name)
{
Type = type;
MapTo = mapTo;
Name = name;
}
What I'm trying to do is to make a public property for that list of objects(in selectedItemsController) so I can use it in other class.
For example I was doing this with name for some Area that is also part of WindowsForm. I was taking the name from some text box and making public property like this:
public string AreaName
{
get { return AreaNameValue.Text; }
set { AreaNameValue.Text = value; }
}
And after that I was able to do this in other class:
var areaName = areaDialog.AreaName.Trim();
So finally my question is does someone know how can I make same public property for DataRow object if the name of DataGrid is for example: tabela? Is there something already defined in DataGrid that I can use? (like 'Text' property is for InputTextBoxes).
You can set your selectedItemsController as the datacontext of your DataGrid. Then you can set and get values on the selectedItemsController itself.
I had bad times trying to figure out how to deal with this. Any help wold be appreciated. Even a suggestion of a better structure that fits to my needs: Construct category items in a category having an specification of how they can be in a category item property list.
This is used to, among other things, dinamicaly generate forms for creating and editing items.
Long story short: I need to know if I'm doing it right or a better (maybe automated) way of deal with it without breaking the whole app.
.
.
I'm working with MySQL 5 in VWD Express 2010 in a Win7 64bit machine with all MySQL drivers intalled (ODBC and .NET specific provider, the last one is not compatible with ASP.Net 4). Other problem rised here, but can be target for a separate question: I'm writing all of my models, 'cause MySql isn't compatible with the Linq to SQL (I can imagine why, but not sure).
.
.
Returning to the real topic:
My models are:
Category - Them main entity, with a name property, a collection of CategoryItemProperty entities and a collection of Item entities;
CategoryItemProperty - An entity with a name and some other properties that dictate how the Items in this category may be (field size, mask, input restriction, etc);
Item - The entity whose properties are based on the category properties;
ItemProperty - The properties of the items (field size, mask, input restriction, etc)
The code is something around this:
public class Category
{
public int CategoryId { get; set }
public string Description { get; set }
//...
public virtual List<CategoryItemProperty> ItemProperties { get; set; }
}
public class CategoryItemProperty
{
public int CategoryItemPropertyId { get; set; }
public string Label { get; set; }
public string Name { get; set; }
public int Size { get; set; }
public int MaxLenght { get; set; }
//...
public virtual Category Category { get; set; }
}
public class Item
{
public int ItemId { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
//...
public virtual Category Category { get; set }
public virtual List<ItemProperty> Properties { get; set; }
}
public class ItemProperty
{
public int ItemPropertyId { get; set; }
public int ItemId { get; set; }
public int CategoryItemPropertyId { get; set; }
public string Value { get; set; }
//...
public virtual Item Item { get; set; }
public virtual CategoryItemProperty CategoryItemProperty { get; set; }
}
.
.
The big problem here, with this approach, is to generate the form and deal with the data on the controller side to be saved to the database.
.
.
A more detailed example wold be: Generate a simple contact form:
We create a Category with some field specification:
var category = new Category() { Description = "Simple Contact Form" };
MyEntitySet.Categories.Add(category);
MyEntitySet.SaveChanges();
//...
var name = new CategoryItemProperty() { Label = "Name", Size = 50, MaxLength = 50 };
var message = new CategoryItemProperty() { Label = "Message", Size = 50, MaxLength = 255 };
category.ItemProperties.Add(name);
category.ItemProperties.Add(message);
MyEntitySet.Entry(category).State = EntityState.Modified;
MyEntitySet.SaveChanges();
.
.
What I have came up until now is to create a ViewModel to pass the category info and its item property collection to the Create and Edit views and doing a loop through the ItemProperties to generate the fields and working in the ItemController, receiving the FormCollection and generating the Item and its ItemPropertys objects and saving them to the database. But this process is terrible and painfull:
.
Items/Create View:
#model MyApp.Models.CategoryItemModelView
#Html.EditorFor(m => m.Description);
...
#foreach(var property in Model.ItemProperties)
{
<label>#property.Label</label>
<input type="text" name="#property.Name" size="#item.Size" maxlength="#item.MaxLength" />
}
In the Controller:
// GET: /Items/Create/5
public ActionResult Create(int id)
{
var categoryItemModelView = new CategoryItemModelView();
categoryItemModelView.Populate(id); // this method maps the category POCO to the ViewModel
return View(categoryItemModelView);
}
// POST: /Items/Create/5
[HttpPost]
public ActionResult Create(int id, FormCollection formData)
{
if (ModelState.IsValid)
{
var category = MyEntitySet.Categories.Find(id);
var item = new Item
{
CategoryId = id,
Description = formData["Description"],
// ...
Category = category
};
MyEntitySet.Items.Add(item);
foreach(var property in category.ItemProperties)
{
var itemProperty = new ItemProperty
{
ItemId = item.ItemId,
CategoryItemPropertyId = property.Id,
Value = form[property.Name],
// ...
Item = item,
CategoryItemProperty = property
};
MyEntitySet.ItemProperties.Add(itemProperty);
}
MyEntitySet.SaveChanges();
return RedirectToAction("Index");
}
// Here I don't know how to return the typed data to the user (the form returns empty)
var categoryItemModelView = new CategoryItemModelView(id);
categoryItemModelView.Populate(id); // this method maps the category POCO to the ViewModel
return View(categoryItemModelView);
}
.
.
My problem rises in building the Create and Edit actions and its respective views (see above how I'm doing it right now). How to handle this case, when I have to use the Category.ItemProperties to generate the fields and store the information in an Item object and the field values in its ItemProperty object?
.
.
Please note: All this code is for example purposes only. My code is similar, but its handled by a specific controller and specific views to CRUD Categories and CategoryItemProperties and I have no problem with this.
.
.
Sorry for this long text. I've tryed to be as clearest as I can. If you need any more info, drop a comment, please.
Okay rcdmk! first of all my English is terrible and i'm here to just share with you my few experience.
I have build such a complex software in the past with MVVM(WPF) + EF4 + T4 to generate POCO's and i deal with Microsoft Blend to handle with actions, bindings and so on between the client and the viewmodels!
that's work great! i hope i helped you!
ps:
I dont know if Blend supports ASP.Net but creating POCO(Viewmodel) with lazy loading could help u somewhere!
As i understand , Category and corresponding CategoryPropertyItems is describing how Item will be created . Simply Category is drawing an abstract form and item and item properties are concretes (because item property has Value property). So in Item/Create Action (GET) you can build item and it's properties using Category and CategoryPropertyItems.
public Item Build(Category category)
{
Item item = new Item();
item.Category = category;
item.ItemId = ...
foreach(var categoryItemProperty in category.ItemProperties)
{
ItemProperty itemProperty = new ItemProperty();
itemProperty.Item = item;
itemProperty.CategoryItemProperty = categoryItemProperty;
itemProperty.ItemPropertyId = ...
}
return item;
}
In result of Index/Create Action you can use either just this Item object or you can put item into ViewModel .
In View you can bind direcly to model (Item) properties .
This links can help you .
Editing and binding nested lists with ASP.NET MVC 2
Model Binding To A List