In my instance of Orchard, I have a custom content type which has a custom content part. In the "editor driver" for the content part, I need to check to see if the container content item is valid (i.e. passes validation).
The normal ModelState won't work here because of how Orchard works - and I can determine if the content part is valid, but I need to know about the entire content item (there are other content parts within the content item).
I know there are ways to execute code once a content part is published / created using lifecycle events (http://docs.orchardproject.net/Documentation/Understanding-content-handlers), but there's no way (that I know of) to pass those events information.
Basically, I need to execute a method if the content item is valid, and I need to pass the method information contained within the ViewModel.
There may be (and probably is) a better way to do this, but I'm struggling to find a way within Orchards framework.
sample code:
//POST
protected override DriverResult Editor(EventPart part, IUpdateModel updater, dynamic shapeHelper)
{
var viewModal = new EventEditViewModel();
if (updater.TryUpdateModel(viewModal, Prefix, null, null))
{
part.Setting = viewModal.Setting;
}
//here's where I need to check if the CONTENT ITEM is valid or not, for example
if (*valid*)
{
DoSomething(viewModal.OtherSetting);
}
return Editor(part, shapeHelper);
}
Note: I am using Orchard version 1.6.
No easy way to do that from inside a driver, I'm afraid. Too early. You can access other parts by doing part.As<OtherPart>, but those may or may not be updated yet at this point.
You may try utilizing handlers and OnPublishing/OnPublished (and other) events like this:
OnPublishing<MyPart>((ctx, part) =>
{
// Do some validation checks on other parts
if (part.As<SomeOtherPart>().SomeSetting == true)
{
notifier.Error(T("SomeSetting cannot be true."));
transactions.Cancel();
}
});
where transactions is ITransactionManager instance, injected in ctor.
If you need more control, writing your own controller for handling item updates/creates is the best way to go.
In order to do that (assuming you already have your controller in place), you need to use handler OnGetContentItemMetadata method to point Orchard to use your controller instead of the default one, like this:
OnGetContentItemMetadata<MyPart>((context, part) =>
{
// Edit item action
context.Metadata.EditorRouteValues = new RouteValueDictionary {
{"Area", "My.Module"},
{"Controller", "Item"},
{"Action", "Edit"},
{"id", context.ContentItem.Id}};
// Create new item action
context.Metadata.CreateRouteValues = new RouteValueDictionary {
{"Area", "My.Module"},
{"Controller", "Item"},
{"Action", "Create"});
});
Related
I need to port a website to asp.net and decided to use Umbraco as the underlying CMS.
The issue I'm having is I need to retain the URL structure of the current site.
The current URL template looks like the following
domain.com/{brand}/{product}
This is hard to make a route for since it mixes in with all the other content on the site. Like domain.com/foo/bar which is not a brand or product.
I've coded up a IContentFinder, and injected it into the Umbraco pipeline, that check the URL structure and determins if domain.com/{brand} matches any of the known brands on the site, in which case i find the content by its internal route domain.com/products/ and pass along {brand}/{model} as HttpContext Items and return it using the IContentFinder.
This works, but it also means no MVC controller is called. So now I'm left with fetching from the database in the cshtml file which is not so pretty and kind of breaks MVC conventions.
What i really wan't is to take the url domain.com/{brand}/{product} and rewrite it to domain.com/products/{brand}/{product} and then being able to hit a ProductsController serving up the content based on the parameters brand and product.
There are a couple of ways to do this.
It depends a bit on your content setup. If your products exist as pages in Umbraco, then I think you are on the right path.
In your content finder, remember to set the page you've found on the request like this request.PublishedContent = content;
Then you can take advantage of Route Hijacking to add a ProductController that will get called for that request: https://our.umbraco.org/Documentation/Reference/Routing/custom-controllers
Example implementation:
protected bool TryFindContent(PublishedContentRequest docReq, string docType)
{
var segments = docReq.Uri.GetAbsolutePathDecoded().Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
string[] exceptLast = segments.Take(segments.Length - 1).ToArray();
string toMatch = string.Format("/{0}", string.Join("/", exceptLast));
var found = docReq.RoutingContext.UmbracoContext.ContentCache.GetByRoute(toMatch);
if (found != null && found.DocumentTypeAlias == docType)
{
docReq.PublishedContent = found;
return true;
}
return false;
}
public class ProductContentFinder : DoctypeContentFinderBase
{
public override bool TryFindContent(PublishedContentRequest contentRequest)
{
// The "productPage" here is the alias of your documenttype
return TryFindContent(contentRequest, "productPage");
}
}
public class ProductPageController : RenderMvcController {}
In the example the document type has an alias of "productPage". That means that the controller needs to be named exactly "ProductPageController" and inherit the RenderMvcController.
Notice that it does not matter what the actual pages name is.
I've created a lookup with two columns, first one containing and integer which works just fine but the second one has a long name and this is where the problem arises. Users should horizontally scroll in order to check the entire string and even in that case, the column's width is not big enough to display the whole data.
I've found this :
Adjusting column width on form control lookup
But i don't understand exactly where and what to add.
I am not sure but maybe I have to add the fact that this lookup is used on a menu item which points to an SSRS report, in the parameters section.
Update 1:
I got it working with a lookup form called like this :
Args args;
FormRun formRun;
;
args = new Args();
args.name(formstr(LookupOMOperatingUnit));
args.caller(_control);
formRun = classfactory.formRunClass(args);
formRun.init();
_control.performFormLookup(formRun);
and in the init method of this form i added:
public void init()
{
super();
element.selectMode(OMOperatingUnit_OMOperatingUnitNumber);
}
meaning the field i really need.
I am not sure i understand the mechanism completely but it seems it knows how to return this exact field to the DialogField from where it really started.
In order to make it look like a lookup, i have kept the style of the Design as Auto but changed the WindowType to Popup, HideToolBar to Yes and Frame to Border.
Probably the best route is do a custom lookup and change the extended data type of the key field to reflect that. In this way the change is reflected in all places. See form FiscalCalendarYearLookup and EDT FiscalYearName as an example of that.
If you only need to change a single place, the easy option is to override performFormLookup on the calling form. You should also override the DisplayLength property of the extended data type of the long field.
public void performFormLookup(FormRun _form, FormStringControl _formControl)
{
FormGridControl grid = _form.control(_form.controlId('grid'));
grid.autoSizeColumns(false);
super(_form,_formControl);
}
This will not help you unless you have a form, which may not be the case in this report scenario.
Starting in AX 2009 the kernel by default auto-updates the control sizes based on actual record content. This was a cause of much frustration as the sizes was small when there was no records and these sizes were saved! Also the performance of the auto-update was initially bad in some situations. As an afterthought the grid control autoSizeColumns method was provided but it was unfortunately never exposed as a property.
you can extends the sysTableLookup class and override the buildFromGridDesign method to set the grid control width.
protected void buildFormGridDesign(FormBuildGridControl _formBuildGridControl)
{
if (gridWidth > 0)
{
_formBuildGridControl.allowEdit(true);
_formBuildGridControl.showRowLabels(false);
_formBuildGridControl.widthMode(2);
_formBuildGridControl.width(gridWidth);
}
else
{
super(_formBuildGridControl);
}
}
I have a standard ASP.Net template, which has a _Layout where my menu is generated. I have multiple data contexts representing different databases throughout my application and all works fine.
I want to add a count as a bootstrap badge next to one of the items in the _Layout. To do this I need to pass in db.TicketDal.Count(). What is the best way to do this directly into the layout. I did try passing the data in a ViewBag entry from the home controller but then when I go to different controllers that doesn't display. I could modify each controller but that seems the wrong way to do it. I suspect I am overthinking this but any advice would be appreciated.
You must create a BaseController. There you can get the var TicketCount = db.TicketDal.Count(); or some List<MenuItems> let's say and any other controllers must inherit from BaseController so in any of them and in any of their methods you would have the same instance of List<MenuItems> or TicketCount
Or you can create a helper class.
public static class BaseKnowledgeHelper
{
public static int GetTicketCount()
{
return db.TicketDal.Count();
}
}
And call that everywhere: #BaseKnowledgeHelper.GetTicketCount()
I am going to suggest what i suggested on a similar post like this.
I would not create a BaseController, this would load and query the DB every single time (which could be ok) and the UI thread is dependent on the DB call.
What I would do is implement an Ajax call to get this information and then put it on your _Layout
Acton Method
public ActionResult GetTicketCount()
{
//Code to fetch the data for the count
return Json(count, JsonRequestBehavior.AllowGet);
}
Ajax on the View
$(function () {
$.ajax({
type: "GET",
url: '#Url.Action("GetTicketCount","WhatEverController")',
success: function (data) {
// You can now do something with the data which contains the count
// e.g. Find the div where the count is suppose to be and insert it.
}
});
});
This way you are not having to wait for any DB calls to finish, the downside is that the count will not appear at the exact same time as your DOM loads. But you could always make it more friendly looking by using something like Spin.js
For my Orchard project, I need some additional information from the user at registration time. (Say, First Name, Last Name, Pants Color). This information must be entered while registering and can not be deferred until later (as per client's orders).
I tried using the Profile and Extended Registration plugins to ask for those, but as far as I see, this only gives me optional fields to display in the registration form. Is there a way to present fields that are mandatory?
I also had a quick foray into overwriting the AccountController's Register method, as per this discussion, but I couldn't get it to work: The controller is in a different place, it can't be subclassed and even if I force it to, code is never executed. I presume they are using a much older version of Orchard.
So, in which direction should I go to create a mandatory field that is close to the Orchard philosophy? Should I create a new field type that rejects empty values maybe? (is that even possible)?
I wrote the ExtendedRegistration module because of that same need.
You need to create a custom part, e.g.: MyRegistrationPart.
Then you add that part to the User ContentType.
In your part just add the [Required] attribute (Data annotations) to any properties that are mandatory.
Registration will not succeed until those mandatory values have been filled out!
Hope it's clear now.
While this probably won't answer your question just wanted to point out that it is my understanding that you don't need to override/subclass the AccountController class. Instead you need to "overwrite" the Users/Account/Register route by adding your own with a higher priority. To do that you need to implement an IRouteProvider as part of our module. Since it's an IDependency it will be loaded and processed automagically at run time. Something like:
public class Routes : IRouteProvider
{
public void GetRoutes(ICollection<RouteDescriptor> routes)
{
routes.AddRange(GetRoutes());
}
public IEnumerable<RouteDescriptor> GetRoutes()
{
return new[] {
new RouteDescriptor {
// Make sure to be higher than the default
Priority = ##### PRIORITY HERE (int) ######,
Route = new Route(
"Users/Account/Register",
new RouteValueDictionary {
{"area", "#### YOUR MODULE AREA HERE ####"},
{"controller", "#### YOUR ACCOUNT CONTROLLER HERE ####"},
{"action", "#### YOUR REGISTER ACTION HERE ####"}
},
new RouteValueDictionary(),
new RouteValueDictionary {
{"area", "#### YOUR MODULE AREA HERE ####"}
},
new MvcRouteHandler())
}
};
}
}
I have a table with records that has delete links. Basically I followed the NerdDinner tutorial for that part in MVC. But I don't want to have the confirm view, I'd rather have a confirm dialog, and then if confirmed let the HttPost action method delete the record directly.
I have something working, but being new to both MVC and jQuery, I'm not sure if I'm doing it right.
Here's the jQuery:
$(function () {
$('.delete').click(function () {
var answer = confirm('Do you want to delete this record?');
if (answer) {
$.post(this.href, function () {
window.location.reload(); //Callback
});
return false;
}
return false;
});
});
And the delete actionlink:
<%: Html.ActionLink("Delete", "Delete", new { id = user.UserID }, new { #class = "delete" })%>
And finally, the delete action method:
[HttpPost]
public ActionResult Delete(int id)
{
_db = new UsersEntities();
try
{
//First delete the dependency relationship:
DeleteUserVisits(id);
//Then delete the user object itself:
DeleteUser(id);
}
catch (Exception)
{
return View("NotFound");
}
return RedirectToAction("Index");
}
Now, I have a few questions about this:
I found the function for making the link POST instead of GET on the internet: `$.post(this.href); return false; And I'm not sure what the "return false" part does. I tried to modify it for my needs with a callback and so on, and kept the return part without knowing what it's for.
Secondly, the action method has the HttpPost attribute, but I have also read somewhere that you can use a delete verb. Should you? And what about the RedirectToAction? The purpose of that was originally to refresh the page, but that didn't work, so I added the window.location.reload instead in a callback in the jQuery. Any thoughts?
The Delete action method calls a couple of helper methods because it seems with the Entity Framework that I use for data, I can't just delete an record if it has relationship dependencies. I had to first delete the relationships and then the "User" record itself. That works fine, but I would have thought it would be possible to just delete a record and all the relationships would be automatically deleted...?
I know you're not supposed to just delete with links directly because crawlers etc could accidentally be deleting records. But with the jQuery, are there any security issues with this? Crawlers couldn't do that when there is a jQuery check in between, right?
Any clarifications would be greatly appreciated!
The return false statement serves
the same purpose as
e.preventDefault() in this case.
By returning false JavaScript is preventing
the browser from executing the link's
default click handler.
The DELETE verb is for RESTful web
services, it is most likely not what
you want in this situation because
not all browsers fully implement it.
Read more about them here: Creating
a RESTful Web Service Using ASP.Net
MVC
The deletion rules for child
entities depend on the entity
OnDelete/OnUpdate rules in the
context definition and also on
foreign key constraints in the
database. You can learn more about
foreign key constraints here.
A crawler will not be able to
activate your delete link in this
fashion because you have specified
the delete action be issued via a
POST. If the delete were a GET then
it would be a concern. Still, it's
not wise to keep links that directly
modify your content on front-facing
pages that do not require
authentication as a human could most
certainly exploit the process.
There you go, with full code :
http://haacked.com/archive/2009/01/30/delete-link-with-downlevel-support.aspx
Or just the html helper :
public static string DeleteLink(this HtmlHelper html, string linkText, string routeName, object routeValues) {
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
string url = urlHelper.RouteUrl(routeName, routeValues);
string format = #"<form method=""post"" action=""{0}"" class=""delete-link"">
<input type=""submit"" value=""{1}"" />
{2}
</form>";
string form = string.Format(format, html.AttributeEncode(url), html.AttributeEncode(linkText), html.AntiForgeryToken());
return form + html.RouteLink(linkText, routeName, routeValues, new { #class = "delete-link", style = "display:none;" });
}
For your questions :
When you do a return false at the end of a javascript click handler on a link, the browser executes the javascript but doesn't follow the link, because of the return false.
For (maximum) cross browser compatibility, you shouldn't use the DELETE verb.
I don't know EF well enough, but doesn't it provide mapping configuration for cascading delete ?
HTTP GET should only be used to get information, for example, provide parameters for a search. Crawlers usually don't care about javascript, so they will blindly follow you links. If it is http://mysite/delete/everything, then, bad for you, if you hadn't the [HttpPost] on you controller action
If you also want to throw the jQuery dialog to the party, this Ricardo Covo post does a good job