loki
loki

Reputation: 2966

how to make a web user control in MVC?

i made an easy web user control by reading Scottgu articles

BUT; my user control return to me error:

ERROR

CountryDropDown.ascx:


<%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%=ViewData["countries"] = new string[] { "France", "Germany", "US", "UK" })%>
<%var q = ViewData["countries"]; %>
<%= Html.DropDownList("",ViewData["countries"] as SelectList)%>

MY VİEW : <%= Html.EditorFor(c=>c.Country,"CountryDropDown") %>

MODEL:

   public class Customer
{
    [Required(ErrorMessage="NameRequired")]
    [StringLength(50,ErrorMessage="Must be less than 50")]
    public string Name { get; set; }
    [Range(1,20,ErrorMessage="Invalid Age")]
    public int Age { get; set; }
    [Required(ErrorMessage="Email Required")]
    [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}")]
    public string Email { get; set; }
    [UIHint("CountryDropDown")]
    public string Country { get; set; }
}

how to make a ASCX in mvc with dropdownlist?

Upvotes: 1

Views: 1180

Answers (2)

user338195
user338195

Reputation:

Change

<%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>

to

<%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Customer>" %>

Assuming Customer is in the root of your namespace.

General remarks, I'm assuming that you are learning MVC and you want to use latest version. Article that you have referred to is for MVC2. I suggest you work through MVC 3 examples on here:

http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part1-cs

Razor syntax should make your life a lot easier. You are also referring to controls (your previous posts). Controls are present in web forms and they are great for when you want to develop components.

MVC is quite different in that sense and you should get a better understanding once you work through the examples.

Upvotes: 0

KingCronus
KingCronus

Reputation: 4529

Using <%= tells ASP to print the following statement. You don't want to be doing that in this case.

<%@ Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% 
    ViewData["countries"] = new string[] { "France", "Germany", "US", "UK" };
    var q = ViewData["countries"]; 
%>
<%= Html.DropDownList("",ViewData["countries"] as SelectList)%>

Try that.

Also, why do you assign q and not use it?

Upvotes: 2

Related Questions