开发者

Asp.Net Mvc templated helpers with interface types

开发者 https://www.devze.com 2023-02-12 15:04 出处:网络
I would like to use the Asp.net MVC templated helpers functionality to generate a standard UI for my objects throughout my application, but I\'ve run into a significant issue:

I would like to use the Asp.net MVC templated helpers functionality to generate a standard UI for my objects throughout my application, but I've run into a significant issue:

I do not directly pass class types from my controllers into their views. Instead, I pass interface types.. with the actual implementation of the Model wrapped up in a Mongo or NHibernate specific class in an indirectly referenced project.

For discussion, my objects look like:

public interface IProductRepository {
    IProduct GetByName(string name);
}

public interface IProduct { 
    string Name { get; set; }
}

public class NHibernateProductRepository : IProductRepository {
    public IProduct GetByName(string name) { 
       /* NHibernate Magic here */
       return nhibernateFoundProduct;
    }
}

public class NHibernateProduct : IProduct {
    public virtual Name { get; set; }
}

public class ProductController : Controller {

    public ProductController(IProductRepository productRepo) {
       _ProductRepo = productRepo;
    }

    public ActionResult Index(string name) {
        IProduct product = _ProductRepo.GetByName(name);
        return View(product);
    }

}

Is it possible to use开发者_JAVA百科 interface types with the Editor.For() syntax? Are there any problems or sticking points that I need to be aware of?

I have an EditorTemplate\IProduct.ascx file available. At this time, I can't seem to get that template to be rendered without hardcoding the "IProduct" name into the Editor.For() call. I would prefer this type of 'Convention over Configuration'....


The templates helpers will use the runtime type of the object for the name. In this case you should name the file NHibernateProduct.ascx

If you don't know the name of the type at design time than you could write a helper method that would inspect the object instance and walk the list of interfaces that a particular type is implementing and return a name based on that. Then you would call the appropriate override to EditorFor that takes the string "templateName" parameter.


I have decided to use an approach with a ViewModel native to the Web project that implements the IProduct interface.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号