How to create a user control in MVC

Hi,

I am using Visual Studio 2013 and MVC5 for developing web application. The scenario is that I have 3 different web applications with some common features. Now in MVC I want to create some sort of user control that contains View, code behind along with  javascript.
Now how I can create such control so that it can be used across all the applications.

Is there something like asp.net server controls or user controls (.ascx) that can be used in MVC application? If no any alternatives for these?

Regards,
Girish

http://blog.davidebbo.com/2011/06/precompile-your-mvc-views-using.html

Steps here

http://www.chrisvandesteeg.nl/2010/11/22/embedding-pre-compiled-razor-views-in-your-dll/

Hi,

Another method is control extensions. Create a public static class. inside that class you can extend any control(set of controls) you want.

eg:

public static class HtmlExtension
    {
	public static IHtmlString CustomDropDownFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, int>> value, Expression<Func<TModel, string>> text, IList dataSource, string key, string css, string changeHandler = "")
        {
	    Dictionary<string, object> attribute = new Dictionary<string, object>();
            attribute.Add("class", css);
            attribute.Add("id", key);

            attribute.Add("onChange", changeHandler);
            MvcHtmlString hdn = InputExtensions.HiddenFor(helper, text, new { id = key });
            MvcHtmlString dropDown = SelectExtensions.DropDownList(helper, "cmb" + key, new SelectList(dataSource, "Key", "Value"), attribute);
            return helper.Raw(hdn.ToHtmlString() + dropDown.ToHtmlString());
        }
    }

The above examples render a dropdown and hidden field. We can use this extension in our views just like other Html extensions. 

@Html.CustomDropDownFor(m => model.Id, m => model.Text, dropdowns, "controlname", "left select","OnChange(this)")

Hi girish.nehte,

Thanks for your post.

According to your description,

girish.nehte

Is there something like asp.net server controls or user controls (.ascx) that can be used in MVC application

I think you can try to use partial view,partial view is like user control.

Please you can check these:

#ASP .NET MVC Partial Views

http://mvc4beginner.com/Tutorial/MVC-Partial-Views.html

#How to Use Partial View in MVC3 and MVC4 with Examples

http://www.c-sharpcorner.com/Blogs/12837/how-to-use-partial-view-in-mvc3-and-mvc4-with-examples.aspx

Hope this can be helpful.

Best Regards,

Eileen

Leave a Reply