[Solved] Adding SelectListItem() class without include System.Web.MVC in C#


You can not achieve this behaviour without adding the namespace, as it stored info about this class.

However, you can create your own select item class and create an extension method for converting items of your class to SelectListItem as following:

public class SimpleItem
{
    public string Text { get; set; }
    public string Value { get; set; }
}

SimpleItem should be stored in assembly to which ViewModels and Views have access.

And in the MVC project create an extension method:

public static class HtmlExtensions 
{
    public static MvcHtmlString LocalDropDownListFor<TModel, TProperty>(
        this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expr, 
        IEnumerable<SimpleItem> items)
    {
        return helper.DropDownListFor(expr, 
            items.Select(x => new SelectListItem { Text = x.Text, Value = x.Value } ));
    }
}

You should include System.Web.Mvc.Html for enabling DropDownListFor method call from helper.

If it is your first HtmlHelper extension, would be better to include namespace of this class into page web.config. Or you will be required to include it on page manually:

@using YourProject.RequiredNamespace

After all you could simple call it on page:

@Html.LocalDropDownListFor(model => model.EmpName, Model.EmpList)

3

solved Adding SelectListItem() class without include System.Web.MVC in C#