How to call Ajax.BeginForm from a custom helper method? - asp.net

Can I call Ajax.BeginFrom from a custom helper method ?
AjaxHelper is not available in a custom helper method, so I tried to pass the "Ajax" available in ViewPage to Helper method while calling it, but then in method, BeginForm is not available on that passed "Ajax" parameter.

You could instantiate it:
public static class HtmlExtensions
{
public static MvcHtmlString Foo(this HtmlHelper htmlHelper)
{
var ajaxHelper = new AjaxHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer);
var form = ajaxHelper.BeginForm();
// ... use the ajaxHelper and htmlHelper
}
}
or if you are writing an extension method on AjaxHelper:
public static class AjaxExtensions
{
public static MvcHtmlString Foo(this AjaxHelper AjaxHelper)
{
var htmlHelper = new HtmlHelper(AjaxHelper.ViewContext, AjaxHelper.ViewDataContainer);
// ... use the ajaxHelper and htmlHelper
}
}
And don't forget the proper usings if you want to bring other extension methods into scope:
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Mvc.Ajax;

Related

Overwriting UrlHelper with a CustomUrlHelper - ASP.NET CORE 2.0

Is there a way to force my ASP.NET Core 2.0 app to use a custom UrlHelper I've written everywhere?
I have a class with custom logic
public class CustomUrlHelper : UrlHelper { ... }
I want it to be used everywhere, so that urls are generated according to our custom business rules.
Create a CustomUrlHelper and a CustomUrlHelperFactory.
public class CustomUrlHelper : UrlHelper
{
public CustomUrlHelper(ActionContext actionContext)
: base(actionContext) { }
public override string Action(UrlActionContext actionContext)
{
var controller = actionContext.Controller;
var action = actionContext.Action;
return $"You wrote {controller} > {action}.";
}
}
public class CustomUrlHelperFactory : IUrlHelperFactory
{
public IUrlHelper GetUrlHelper(ActionContext context)
{
return new CustomUrlHelper(context);
}
}
Then open your Statup.cs file and register the CustomUrlHelperFactory in the ConfigureServices method.
services.AddMvc();
services.AddSingleton<IUrlHelperFactory, CustomUrlHelperFactory>();
After doing that, your app will use the CustomUrlHelper everywhere. That includes calls to #Url.Action("Index", "Home") from a razor page.

How can I customise how Razor converts values of certain types to text?

Imagine I have some custom type:
public class CustomType
{
public override string ToString() {
return "Default";
}
}
Next, imagine I use an instance of this type in a Razor view:
#model CustomType
<span>The custom type is #Model</span>
Razor seems to use ToString to convert the value into text for the resulting HTML. However, I want to tell Razor that whenever it wants to format a CustomType, it should use some given custom formatting logic.
Is this possible? If so, how can I do it?
You could do it with an HtmlHelper
#Html.CustomFormattingLogic(Model)
public static class MyHtmlHelperExtensions
{
public static MvcHtmlString CustomFormattingLogic(this HtmlHelper htmlHelper,
CustomType model)
{
var customString = MethodToDoFormatting(model);
return MvcHtmlString.Create(customString);
}
}
...as another option, you could have an extension method do custom formatting:
public static class MyCustomTypeExtensions
{
public static string CustomFormattingLogic(this CustomType model)
{
var customString = MethodToDoFormatting(model);
return customString;
}
}

Use TagBuilder in webform project?

I have a old webform project that I have now set to .net 4.0. I have added the System.Web.MVC ref 4.0 but the TabBuilder do still not show up as a known type?
Edit : I have also tried adding System.Web.WebPages 2.0 but that do not solve the problem.
Please test this code and see this maybe you forget using
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1.Helpers
{
public static class ImageHelper
{
public static string Image(this HtmlHelper helper, string id, string url, string alternateText)
{
return Image(helper, id, url, alternateText, null);
}
public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
{
// Create tag builder
var builder = new TagBuilder("img");
// Create valid id
builder.GenerateId(id);
// Add attributes
builder.MergeAttribute("src", url);
builder.MergeAttribute("alt", alternateText);
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return builder.ToString(TagRenderMode.SelfClosing);
}
}
}

RedirectToAction alternative

I'm using ASP.NET MVC 3.
I've wriiten a helper class as follows:
public static string NewsList(this UrlHelper helper)
{
return helper.Action("List", "News");
}
And in my controller code I use it like this:
return RedirectToAction(Url.NewsList());
So after the redirect the link looks like this:
../News/News/List
Is there an alternative to RedirectToAction? Is there a better way that I need to implement my helper method NewsList?
Actually you don't really need a helper:
return RedirectToAction("List", "News");
or if you want to avoid hardcoding:
public static object NewsList(this UrlHelper helper)
{
return new { action = "List", controller = "News" };
}
and then:
return RedirectToRoute(Url.NewsList());
or another possibility is to use MVCContrib which allows you to write the following (personally that's what I like and use):
return this.RedirectToAction<NewsController>(x => x.List());
or yet another possibility is to use T4 templates.
So it's up to you to choose and play.
UPDATE:
public static class ControllerExtensions
{
public static RedirectToRouteResult RedirectToNewsList(this Controller controller)
{
return controller.RedirectToAction<NewsController>(x => x.List());
}
}
and then:
public ActionResult Foo()
{
return this.RedirectToNewsList();
}
UPDATE 2:
Example of unit test for the NewsList extension method:
[TestMethod]
public void NewsList_Should_Construct_Route_Values_For_The_List_Action_On_The_News_Controller()
{
// act
var actual = UrlExtensions.NewsList(null);
// assert
var routes = new RouteValueDictionary(actual);
Assert.AreEqual("List", routes["action"]);
Assert.AreEqual("News", routes["controller"]);
}

sharp architecture question

I am trying to get my head around the sharp architecture and follow the tutorial. I am using this code:
using Bla.Core;
using System.Collections.Generic;
using Bla.Core.DataInterfaces;
using System.Web.Mvc;
using SharpArch.Core;
using SharpArch.Web;
using Bla.Web;
namespace Bla.Web.Controllers
{
public class UsersController
{
public UsersController(IUserRepository userRepository)
{
Check.Require(userRepository != null,"userRepository may not be null");
this.userRepository = userRepository;
}
public ActionResult ListStaffMembersMatching(string filter) {
List<User> matchingUsers = userRepository.FindAllMatching(filter);
return View("ListUsersMatchingFilter", matchingUsers);
}
private readonly IUserRepository userRepository;
}
}
I get this error:
The name 'View' does not exist in the current context
I have used all the correct using statements and referenced the assemblies as far as I can see. The views live in Bla.Web in this architecture.
Can anyone see the problem?
Thanks.
Christian
You should inherit UsersController from System.Web.Mvc.Controller class. View() method is defined in Controller class.
public class UsersController : Controller
{
//...
}

Resources