HtmlHelpers are really useful, also i was using AjaxHelpers untill i wanted to do something they can't... so now i'm prefering jquery+javascript, but i don't like to write in javascript (mayby because i never know it as good as i wanted) and to make life easier i wanted to implement something like JQueryHelper, but right now i don't know how
I wanted to use inside of "Helper" resolved URL's, because most methods would just pass data to controllers etc... and update some parts of UI, so i'd like to create something like AjaxHelper, but based on JQuery, not MSScripts.
What should I include in such class? how can i get context, url's and generate proper javascript code which can by dynamicly injected into
ex.
<div onclick=JQuery.Action("<ActionName>", "<Controller>", new { param1, param2}, <Id to Update>)> My Div</div>
How is it implemented in HtmlHelper or AjaxHelper?
Edit:
I've tried few simple implementation, but i think I'm lack of knowledge and don't know how to implement class with extensions exacly.
I've ClassA(class) and ClassAExt(extensions):
I've something like that:
static public class ClassAExt{
public static MvcHtmlString Method(this ClassA classA) {
}
}
But in View(), when I'm using ClassAExt.Method() i have to pass also instance of ClassA (in helpers Ajax and Html this argument is grey (optional? not needed?), how to get such effect).
I am not sure if I understand your question correctly.
The HtmlHelper also get instantiated (i.e. new HtmlHelper()) during the course of page rendering and user control rendering. Ajax and URL helpers also get instantiated and this is what give one access to the various variables such HttpContext etc.
So in order for you to use your helper class related to ClassA you too will need to instantiate it. I think then the question leads to how do I do this? You will probably need to extend the ViewPage, ViewUserControl and ViewMasterPage classes.
Its non obvious because its so obvious. Basically, you extend html helper's extension:
public static HtmlString Foo(this HtmlHelper helper, string param)
{
//do whatever
}
You can get at request context, etc, from HtmlHelper.
Way I see it, you problem is that you don't understand extension methods.
if you have
static public class ClassAExt{
public static MvcHtmlString Method(this ClassA classA) {
}
}
you use it in view like this:
<%: ClassAInstance.Method() %>
to do that, you have to add <add namespace="NamespaceOfClassA" /> to you web.config's pages/namespaces section.
This way, you can extend the HtmlHelper class to do whatever you need, so there is really nothing it can't do. If you want it to do something it can't by default, just write an extension method. Also download MVC Futures assembly, there's a dll Microsoft.Web.Mvc that contains (among other things) a lot of useful extension methods for HtmlHelper.
If you want to know how they implemented HtmlHelper or AjaxHelper you can check out MVC source code.
Link to download both MVC Futures and MVC source code: http://aspnet.codeplex.com/releases/view/41742
Related
I have the following situation. There are two combos on my UI form, one shows the list of vegetables and another one shows a list of fruits.
In my supporting view class I'd like to declare such methods:
#UiFactory
SimpleComboBox<Vegetable> createVegetablesCombo() {
return vegetables;
}
#UiFactory
SimpleComboBox<Fruit> createFruitsCombo() {
return fruits;
}
But it seems that GWT does not recognize parameterized returned types... Every time I get an error:
ERROR: Duplicate factory in class VegetablesAndFruitsView for type SimpleComboBox.
Is it possible to handle this case? Is there a good example of multiple comboboxes on one UI form?
From the perspective of Java (not GWT, not UiBinder, but the Java language itself) at runtime there isn't a difference between SimpleComboBox<Vegetable> and SimpleComboBox<Fruit>. That said, this error is coming from UiBinder's code generation, which is looking for all #UiConstructor methods, and using them to build things.
So what does UiBinder have to work with? From the UiBinder XML, there is no generics. The only way UiBinder could get this right is if you happen to have included a #UiField entry in your class with the proper generics. This then would require #UiField annotations any time there might be ambiguity like this, something GWT doesn't presently do.
What are you trying to achieve in this? You are returning a field (either vegetables or fruits) - why isn't that field just tagged as #UiField(provided=true)? Then, whatever wiring you are doing to assign those fields can be used from UiBinder without the need for the #UiConstructor methods at all.
#UiField(provided=true)
SimpleComboBox<Fruit> fruits;
//...
public MyWidget() {
fruits = new SimpleComboBox<Fruit>(...);
binder.createAndBind(this);
}
...
<form:SimpleComboBox ui:field="fruits" />
If this is just an over-simplification, and you actually plan on creating new objects in those methods, then consider passing an argument in, something like String type, and returning a different SimpleComboBox<?> based on the value. From your UiBinder xml, you could create the right thing like this:
<field:SimpleComboBox type="fruit" />
The Header section (Apache Tiles Attribute) is shared by several views. It has a form that expects an Object when the page is loaded and complains if the Object is missing. At the moment I am placing the Object in a Model and passing it to the View using the Controller every time I create a view that inherits this layout.
This approach seems rather tedious as i have repeated lines all over the Controller. I'd like to be able to add it once and be done with.
I am not too familiar with Apache Tiles there maybe a simple solution that I am not aware of.
Looking for some helpful tips.
Thanks
You can use the HandlerInterceptorAdapter class and the postHandle method to achieve something like that. By cons, you will need to define a rule that will help you to know when the object need to be add to the model, it can be the path or something in the url, it depends on how your template is organized. Here an example of an interceptor that is doing something like that.
The interceptor defenition :
<mvc:interceptors>
<bean class="your.package.HeaderModelInterceptor"/>
</mvc:interceptors>
The interceptor class :
public class HeaderModelInterceptor extends HandlerInterceptorAdapter {
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// Check if you need to add the object
if (Your rule) {
modelAndView.addObject("headerObject", headerObject);
}
super.postHandle(request, response, handler, modelAndView);
}
}
You have a couple of options to do this. Off the top of my head you could.
Use Tiles view preparers, simple example here
Use a mechanism like Spring interceptors or AOP to automatically add your object to the Model instead of repeating the code everywhere
It really depends on the nature of the object you're adding and how much context it needs.
I've been looking around for an answer to this, which I can't believe hasn't been asked before, but with no luck I'm attempting here.
I have a signup form which differs slightly based upon what type of participant the requester is. While writing tests for the solution, I realized that all actions did the same things, so I'm attempting to combine the actions into one using a strategy pattern.
public abstract class BaseForm { common properties and methods }
public class Form1 : BaseForm { unique properties and overrides }
....
public class FormX : BaseForm { unique properties and overrides... in all about 5 forms }
Here is the combined action:
[ModelStateToTempData, HttpPost]
public ActionResult Signup(int id, FormCollection collection)
{
uiWrapper= this.uiWrapperCollection.SingleOrDefault(w => w.CanHandle(collection));
// nullcheck on uiWrapper, redirect if null
var /*BaseForm*/ form = uiWrapper.GetForm(); // Returns FormX corresponding to collection.
this.TryUpdateModel(form, collection.ToValueProvider()); // Here is the problem
form.Validate(this.ModelState); // Multi-Property validation unique to some forms.
if (!this.ModelState.IsValid)
return this.RedirectToAction(c => c.Signup(id));
this.Logic.Save(form.ToDomainClass());
return this.RedirectToAction(c => c.SignupComplete());
}
The problem I'm having is that TryUpdateModel binds only the common properties found in BaseForm. My previous code used public ActionResult FormName(int id, FormX form) which bound properly. However, I did some testing and discovered that if I replace var form with FormX form the form binds and everything works, but I'm back to one action per form type.
I'm hoping to find a way to get this to bind properly. form.GetType() returns the proper non-base class of the form, but I'm not sure of how to grab the constructor, instantiate a class, and then throw that into TryUpdateModel. I know that the other possibility is a custom ModelBinder, but I don't see a way of creating one without running into the same FormBase problem.
Any ideas or suggestions of where to look?
I was trying to do something similar to Linq, I was trying to create a class that would inherit some standard fields (ID, etc). I found that the default Linq engine would only use fields from the instantiated class, not from any inherited classes or interfaces.
To construct a Type simply use code like:
var form = Activator.CreateInstance(uiWrapper.GetForm());
I figured it out!
Erik's answer wasn't the solution, but for some reason it made me think of the solution.
What I really want form to be is a dynamic type. If I change this line:
dynamic form = uiWrapper.GetForm();
Everything works :)
On top of that, logic.Save(form.ToDomainClass()) also goes directly to Save(DomainTypeOfForm) rather than Save(BaseDomainForm) so I can avoid the headache there as well. I knew that once I figured out the problem here I could apply the answer in my logic class as well.
i'm trying to dynamically add the class attribute to the body tag, and i came across this class. but i can't seem to understand how to use this class. i have something like this in my page class (or panel class, as i tried with that too):
add(new BodyTagAttributeModifier("class", "homepage", this));
this doesn't even compile, saying there's something wrong with the 2nd parameter. but i think String is automatically considered a Model in wicket, like the Label class. am i missing something here?
What if you just add an wicket:id to the body attribute and use the AttributeAppender class? Or, if the body attribute already has an id, can't you just use this class?
http://wicket.sourceforge.net/apidocs/wicket/behavior/AttributeAppender.html
Some Wicket Components have this String-to-model-shortcut (like Label), but it's not a general feature. You have to convert your String into a Model manually:
add(new BodyTagAttributeModifier("class", Model.of("homepage"), this));
I want to handle different types of docs the same way in my application
Therefore:
I have a generic interface like this.
public interface IDocHandler<T>where T: class
{
T Document { get;set;}
void Load(T doc);
void Load(string PathToDoc);
void Execute();
void Execute(T doc);
}
And for different types of documents I implement this interface.
for example:
public class FinanceDocumentProcessor:IDocumentHandler<ReportDocument>
{}
public class MarketingDocumentProcessor:IDocumentHandler<MediaDocument>
{}
Then I can do of course something like this:
IDocumentHandler<ReportDocument> docProc= new FinanceDocumentProcessor();
It would be interessting to know how I could inject T at runtime to make the line above loosly coupled...
IDocumentHandler<ReportDocument> docProc = container.resolve("FinanceDocumentProcessor());
but I want to decide per Configuration wether I want to have my FinanceDomcumentProcessor or my MarketingDocumentProcessor... therefore I would have to inject T on the left site, too ...
Since I have to use c# 2.0 I can not use the magic word "var" which would help a lot in this case... but how can I design this to be open and flexible...
Sorry for the misunderstanding and thanks for all the comments but I have another example for my challenge (maybe I am using the wrong design for that) ...
But I give it a try: Same situation but different Explanation
Example Image I have:
ReportingService, Crystal, ListAndLabel
Three different Reporting Document types. I have a generic Handler IReportHandler<T> (would be the same as above) this Handler provides all the functionality for handling a report Document.
for Example
ChrystalReportHandler:IReportHandler<CrystalReportDocument>
Now I want to use a Framework like Unity (or some else framework) for dependency injection to decide via configuration whether I want to use Crystal, Reportingservices or List and Label.
When I specify my mapping I can inject my ChrystalReportHandler but how can I inject T on the left side or in better word The Type of ReportDocument.
IReportHandler<T (this needs also to be injected)> = IOContainer.Resolve(MyMappedType here)
my Problem is the left Site of course because it is coupled to the type but I have my mapping ... would it be possible to generate a object based on Mapping and assign the mapped type ? or basically inject T on the left side, too?
Or is this approach not suitable for this situation.
I think that with your current design, you are creating a "dependency" between IDocumentHandler and a specific Document (ReportDocument or MediaDocument) and so if you want to use IDocumentHandler<ReportDocument or MediaDocument> directly in your code you must assume that your container will give you just that. The container shouldn't be responsible for resolving the document type in this case.
Would you consider changing your design like this?
public interface IDocumentHandler
{
IDocument Document { get; set; }
void Load(IDocument doc);
void Load(string PathToDoc);
void Execute();
void Execute(IDocument doc);
}
public class IDocument { }
public class ReportDocument : IDocument { }
public class MediaDocument : IDocument { }
public class FinanceDocumentProcessor : IDocumentHandler { }
public class MarketingDocumentProcessor : IDocumentHandler { }
If I understand you correctly, you have two options.
if you have interface IDocHandler and multiple classes implementing it, you have to register each type explicitly, like this:
container.AddComponent>(typeof(FooHandler));
if you have one class DocHandler you can register with component using open generic type
container.AddComponent(typeof(IDocHandler<>), typeof(DocHandler<>));
then each time you resolve IDocHandler you will get an instance of DocHandler and when you resolve IDocHandler you'll get DocHandler
hope that helps
You need to use a non-generic interface on the left side.
Try:
public interface IDocumentHandler { }
public interface IDocumentHandler<T> : IDocumentHandler { }
This will create two interfaces. Put everything common, non-T-specific into the base interface, and everything else in the generic one.
Since the code that you want to resolve an object into, that you don't know the type of processor for, you couldn't call any of the T-specific code there anyway, so you wouldn't lose anything by using the non-generic interface.
Edit: I notice my answer has been downvoted. It would be nice if people downvoting things would leave a comment why they did so. I don't care about the reputation point, that's just minor noise at this point, but if there is something seriously wrong with the answer, then I'd like to know so that I can either delete the answer (if it's way off target) or correct it.
Now in this case I suspect that either the original questionee has downvoted it, and thus either haven't posted enough information, so that he's actually asking about something other than what he's asked about, or he didn't quite understand my answer, which is understandable since it was a bit short, or that someone who didn't understand it downvoted it, again for the same reason.
Now, to elaborate.
You can't inject anything "on the left side". That's not possible. That code have to compile, be correct, and be 100% "there" at compile-time. You can't say "we'll tell you what T is at runtime" for that part. It just isn't possible.
So the only thing you're left with is to remove the T altogether. Make the code that uses the dependency not depend on T, at all. Or, at the very least, use reflection to discover what T is and do things based on that knowledge.
That's all you can do. You can't make the code on the left side change itself depending on what you return from a method on the right side.
It isn't possible.
Hence my answer.