Description(and many attributes) for User Control are not displaying info - asp.net

I want to show some description information of my User Control in the Propereties toolbox.
After writting some attributes for the control:
public partial class WebUserControl1 : System.Web.UI.UserControl
{
int id;
[Description("Get or Set the main name of the css class to apply")]
public string CssClass { get; set; }
[Description("Get the number of nodes")]
public int NodesCount
{
get
{
return id;
}
}
[Browsable(true),
Category("Behavior"),
DefaultValue(""),
Description("The Uri to find the Xml file"),
Editor(typeof(System.Web.UI.Design.XmlUrlEditor), typeof(UITypeEditor))]
public string XmlPath { get; set; }
There are no answer from the toolbox
Any Ideas?

I have confirmed this yet, but I have read that you if you create the WebUserControl in a separate project and add the .dll reference, you will then get the design time support you are looking for.

Related

Using (showing) data from another model from my current view

No code to show. I just want to understand something. I already do some MVC code (I have a model, I ask Visual Studio to create Controller and View).
Each view has only "ONE MODEL" associated. So, with Razor, I can show data from this model. I play with my code and I understand it up to now.
BUT ...
On the same view, HOW we can work with another MODEL ?
For me, a model is simply a class with properties, etc. My database has an equivalent "data table" for each model. I can manipulate it with Entity Framework ... no problem. But, I need to use DATA from different model (different table) in the SAME VIEW and Visual Studio does not give me permission to use another MODEL in the view.
What is the strategy ? (or maybe I don't understand something ...)
Thank you.
The strategy is to build a view model, a model built to be displayed, and represents the data that you need to use.
Example :
You have these classes, classes who are a representation of your database :
public class FootballTeam{
public string Name{get;set;}
public string Logo{get;set;}
}
public class FootballGame{
public Datetime Date {get;set;}
public string Competition {get;set;}
}
public class Referee{
public string Name{get;set;}
public int Experience {get;set;}
}
To display information about a match game, you can create a view model for this, class who can references some classes of your business model if necessary :
public class GameViewModel{
[DisplayName("Home team")]
public FootballTeam HomeTeam{get;set;}
[DisplayName("Referee")]
public Referee Referee{get;set;}
[DisplayName("Visitor team")]
public FootballTeam VisitorTeam {get;set;}
[DisplayName("Comments")]
public List<string> RedactionComments{get;set;}
}
And create a view who will consume this GameViewModel.
In general, when you create a new MVC project, your have a folder named "ViewModels" in your presentation layer who contains some classes like this one.
This method allows to separate your business model to your presentation model, which are 2 completely different things.
There are very good answers here : What is ViewModel in MVC?
You can update your model type of your razor view to any type you want. It will work as long as you are passing that type from your action method.
Simply open up the razor view and change the line where it says what type the model is.
#model Customer
Now you need to make sure that you are passing a Customer object from your action
public ActionResult Create()
{
return View( new Customer());
}
Also when you create a view, You do not need to necessarily select the Model type in the Dialog box. You can keep that empty and add it to the razor view as needed ( as shown above)
If you want to bring data from 2 different table, Create a new view model which has properties needed for the view and use that as your view's model type.
You should use ViewModal to Create a ViewModal that will be combination of two modals properties as per our need
ViewModel contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view with Own Defined Modals
Understand how to use View Modal in MVC From Link Below -
Understand View Modal In MVC
CODE THAT DEMONSTRATE HOW TO USE VIEWMODALS IN MVC
Product.cs
public class Product
{
public Product() { Id = Guid.NewGuid(); }
public Guid Id { get; set; }
public string ProductName { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
}
ProductCategory.cs
public class ProductCategory
{
public int Id { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
ProductViewModel.cs
public class ProductViewModel
{
public Guid Id { get; set; }
[Required(ErrorMessage = "required")]
public string ProductName { get; set; }
public int SelectedValue { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
[DisplayName("Product Category")]
public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

Is there a way to specify .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) as a decorator to my entity?

I have the following class. I was using a mapping file but I would not like to decorate the class with the different options. I already have in my mapping file:
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
How can I set this or set another option of DatabaseGeneratedOption by decorating the class? I looked at the Intellisense options but can't find one for this all I can find is [DatabaseGenerated()] and I am not sure if that's correct or how to set that option:
[DatabaseGenerated()]
public class ContentType : Entity
{
public ContentType()
{
this.Contents = new List<Content>();
}
[Key]
public int ContentTypeId { get; set; }
public string Name { get; set; }
public virtual ICollection<Content> Contents { get; set; }
}
DatabaseGenerated is Property and Field specific attribute. You can't add it to a class, only specific properties or fields.

Updating From Database Causes Redoing The Inheritance

Using EF 5. Below is Model.cs file under the Model.tt
I was suggested to have an interface to be inherited by all the entities on the model for some reason. You see the two of them (Adress, Kids) below.
public interface IHasAutoID
{
int getAutoId();
}
public partial class Adress : IHasAutoID
{
public int ID { get; set; }
public Nullable<System.DateTime> date{ get; set; }
..
..
}
public partial class Kids : IHasAutoID
{
public int ID { get; set; }
public Nullable<System.DateTime> date { get; set; }
..
}
Whenever I "Update Model From Database", as the "Tables" are not selectable(I don't know why), I need to delete the whole model and create new connection to the database. No problem at all. But this causes interface inheritance goes missing. every time I need to inherit all entities(almost 50) from "IHasAutoID" interface. I need your expertise.
You can create separate partial classes that contain your customizations. This is how I would do it (assuming that each class has public int ID):
public interface IHasAutoID
{
int ID { get; set; }
int GetAutoId();
}
public partial class Address : IHasAutoID
{
public int GetAutoId()
{
return this.ID;
}
}
Note that this is a class beside the Address class generated by EF. By using an interface you have to implement the GetAutoId() in each partial class. An alternative could be to do this in an abstract base class. Personally, I prefer interfaces despite the larger amount of boilerplate code. Inheritance often complicates code more than necessary.
A third alternative is to modify the t4 template to include the interface and its implementation in the generated code. It's not too hard. (But it usually takes some trial and error).
One last comment: you apparently want get generated ID values. But these values are returned into new entities after EF executes SaveChanges, maybe you don't even need this interface?
Modify Model.tt
public string EntityClassOpening(EntityType entity)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1}partial class {2}{3} : IHasAutoID",
Accessibility.ForType(entity),
_code.SpaceAfter(_code.AbstractOption(entity)),
_code.Escape(entity),
_code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType)));
}
add namespace of IHasAutoID
public string UsingDirectives(bool inHeader, bool includeCollections = true)
{
return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion())
? string.Format(
CultureInfo.InvariantCulture,
"{0}using System;{1}" +
"{2}using YourNamespace of IHasAutoID;",
inHeader ? Environment.NewLine : "",
includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "",
inHeader ? "" : Environment.NewLine)
: "";
}

ASP.Net MVC3 conditional validation

I'm having some troubles with validation on my application.
Let's say I've the following models:
public class Company
{
public int id { get; set; }
[Required]
public String Name { get; set; }
public String Location { get; set; }
public List<Contacts> Contacts { get; set; }
}
public class Contact
{
public int id { get; set; }
[Required]
public String Name { get; set; }
[DataType(DataType.EmailAddress)]
public String Email { get; set; }
public String Telephone { get; set; }
public String Mobile { get; set; }
}
Now in my company create view I've two buttons, one to add contacts to the company, and another one to create the new company.
I detected which button was used in my controller like this (both buttons are named "button"):
[HttpPost]
public ActionResult Create(String button, FormCollection collection)
{
if(button == "AddContact")
{
AddContact(collection);
}
else
{
CreateCompany(collection);
}
}
While it's being created the object that represents the company that it's being create is stored in the session (for example HttpContext.Session["company"] = company;)
Now the problem is that if, for example, I try to add a contact without first specifying the company name, i get a validation error because the company name is required, which shouldn't happen because the user might want to add the contacts before adding the company info. Or if I try to save the company, I also get a validation error, because usually when saving the "add contact" form is empty, which means that the contact name (which is required as well) was not specified.
What I want to know is that if it's possible to validate the contact properties only when the addContact button is used, and validate the company properties only when the createCompany button is pressed.
For now i only need to do this serve-side, but if anyone has a solution to do this client-side as well i would appreciate the help.
You could trigger your own validation on the individual objects using
Validator.TryValidateObject(Object, ValidationContext, ICollection)
You can provide conditional validation using the Entity Framework by overriding DbEntityValidationResult in the DbContext. When this validation occurs in the DbContext you can access other entities. When validating a contact you can check the company too. For example:
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
var result = base.ValidateEntity(entityEntry, items);
ValidateContact(result);
return result;
}
private void ValidateContact(DbEntityValidationResult result)
{
var contact= result.Entry.Entity as Contact;
if (contact!= null && contact.ContactId != 0)
{
// Add validation code here, such as:
if(!string.IsNullOrEmpty(contact.Company.Name){
result.ValidationErrors.Add(
new DbValidationError(
"Contact",
"Company name cannot be null or empty when validating contacts.")
);
}
}
}
See Julia Lerman's Programming Entity Framework: DbContext http://www.amazon.com/Programming-Entity-Framework-Julia-Lerman/dp/1449312969 for more details.

Populate dropdownlist from another dropdownlist with objects in MVC 2

I am trying to develop a simple MVC 2 timesheet application for my small business.
I have a sort of mock model for now until I have a database in place, just to make things simpler while I develop the functionality. It consists of the following:
public class CustomersRepository
{
public CustomersRepository()
{
Customers = new List<Customer>();
}
public List<Customer> Customers { get; set; }
}
public class Task
{
public Task()
{
Customer = new Customer();
TimeSegments = new List<TimeSegment>();
}
public override string ToString()
{
return Name;
}
public string Name { get; set; }
public Customer Customer { get; set; }
public List<TimeSegment> TimeSegments { get; set; }
}
public class TimeSegment
{
public string Id { get; set; }
public string Date { get; set; }
public int Hours { get; set; }
}
public class Customer
{
//To show the name in the combobox instead of the object name.
public override string ToString()
{
return Name;
}
public Customer()
{
Tasks = new List<Task>();
}
public List<Task> Tasks { get; set; }
public string Name { get; set; }
}
I initialize the repository in the controller, and pass the "model" to the view:
CustomersRepository model = new CustomersRepository();
public ActionResult Index()
{
InitializeRepository();
return View(model);
}
Now, in the view I populate a dropdownlist with the customers:
<div>
<%:Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers), new {#id="customerDropDownList"}) %>
</div>
But then I need to populate a second dropdownlist (taskDropDownList for the tasks associated with a particular customer) based on the selection the user chooses in the customer dropdownlist.
But how do I do this exactly? I have seen examples with jQuery, but I'm not sure how to apply them to this situation. Also, the examples seem to just populate the lists with string values. I need to be able to access the objects with all their properties. Because the next thing I need to do is to be able to populate the TimeSegments list of the selected task with values from input fields (i.e. the hours worked for particular dates). And for that to be saved to the "model" (eventually to the database) in the controller, how do I get it there, unless the objects are all part of the same model bound to the View?
I'm on rather thin ice with this since I still find the connection between the View and the Controller hard to handle, compared with e.g. Windows development, where these things are rather easy to do. So I would really appreciate a good step by step example if anyone would be so kind as to provide that!
I found the answer here:
http://www.pieterg.com/post/2010/04/12/Cascading-DropDownList-with-ASPNET-MVC-and-JQuery.aspx
It needed some tweaks, and I got help here from CGK. See this post:
Cascading dropdownlist with mvc and jQuery not working

Resources