Rendering Javascript via custom HTML Helper extension method? - asp.net-mvc

In our ASP.NET MVC3 project we have written couple of custom HTML Helper extension method, which basically renders some composit controls (say a text and a label with some needed styles). Now we also want to render some javascript along with HTML tags, but looks MVCHtmlString does not render javascript test as javascript ! Any options or alternatives to render dynamic javascript from custom HTML Helpers ?

It works fine for me :)
here is what I used as an extension method:
namespace MvcApplication1.ExtensionMethods
{
public static class MyExtensionMethods
{
public static MvcHtmlString SomeJavascript(this HtmlHelper helper)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script> alert('testing 123')</script>");
return MvcHtmlString.Create(sb.ToString());
}
}
}
and in my index.cshtml i call it like this:
#using MvcApplication1.ExtensionMethods
....
#Html.SomeJavascript()
and it shows me the pop-up :)

Related

Is it possible Render MVC control using a method

We are working on an MVC application. As per requirement, we need to populate a VIEW using a method. I have created a sample application. You can see the method which is using to generate control in Helper.cs class under “Controller” folder. When we directly placing the #Html.TextBox("SampleTextBox") code in the view it is rendering correctly. But when we generate the same code using a method, it is not rendering properly and it is showing as a plain string.
If anybody has any idea regarding this please let us know, it would be very helpful.
Sample code
Instead of adding the following code directly to view, we need to populate it using a method.
#Html.TextBox("SampleTextBox")
That is some thing like
#Html.Raw(Helper.GetStringCode())
Method:
public static string GetStringCode()
{
return "#Html.TextBox(\"SampleTextBox\")";
}
You could add a partial view for the Kendo Grid in the Shared folder and add an Html helper extension that returns your partial view:
Partial view Shared/_KendoGrid.cshtml:
#model CustomViewModel
#(Html.Kendo().Grid()...)
Html helper method:
public static MvcHtmlString KendoGrid(this HtmlHelper helper, string header)
{
return helper.Partial("Shared/_KendoGrid", new CustomViewModel { Header = header });
}
In your .cshtml:
#Html.KendoGrid("Custom header")

Emit JS code from an HTML helper MVC

Say I want to write an HTML helper to draw a chart.
This helper would need to emit specific JS script code into the body of the page it was called from.
Is this recommended ?
If not how would i workaround that ?
Can i tell the helper to emit the code into a specific section defined in the main layout ?
This should do it:
public static class HtmlHelperExtensions
{
public static MvcHtmlString HelloWorld(this HtmlHelper helper)
{
return new MvcHtmlString("alert('Hello World');");
}
}
In Your Razor View:
<script type="text/javascript">
#Html.HelloWorld();
</script>
You probably should not be doing this.
I would consider JS front end content that forms part of your view. Your view should simply display your view model.
I would be interested in knowing why you feel you need to be able to deliver JS in this way?

Accessing Model object in a custom Html helper

I'm trying to create a custom HTML helper and I would like to know how I can access the Model object without passing it as a parameter.
Thanks
If you are using strongly typed views which you should:
public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> htmlHelper)
{
TModel model = htmlHelper.ViewData.Model;
return MvcHtmlString.Empty;
}
If you are not using strongly typed views which you shouldn't:
public static MvcHtmlString MyHelper(this HtmlHelper htmlHelper)
{
object model = htmlHelper.ViewData.Model;
return MvcHtmlString.Empty;
}
HTML helpers are a bad way to generate HTML programmatically. Web Forms is much better with code in a page class file and HTML markup in a separate file. Yes HTML helpers put some code in separate class files but you are calling code from your HTML page. Whats to stop you from writing code directly in your view page. MVC is supportive of lots of bad practices which you don't have to do but for some reason in Web Forms developers have to do bad practices because it is allowed. If you learn Web Forms well, you will develop maintainable and scalable web applications using modern object oriented patterns instead of procedural logic like HTML helpers.

Using html helpers in Razor web helper

I am trying to create a Razor web helper something like this :
#helper DisplayForm() {
#Html.EditorForModel();
}
But this gives the error "CS0103: The name 'Html' does not exist in the current context".
Is there any way to reference html helpers within web helpers?
You can cast the static Page property from the context to the correct type:
#helper MyHelper() {
var Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;
Html.RenderPartial("WhatEver");
#Html.EditorForModel();
}
Declarative helpers in Razor are static methods. You could pass the Html helper as argument:
#helper DisplayForm(HtmlHelper html) {
#html.EditorForModel();
}
#DisplayForm(Html)
Razor inline WebHelper is generate static method.
So can not access instance member.
#helper DisplayForm(HtmlHelper html){
#html.DisplayForModel()
}
How about this?

Create an ActionLink with HTML elements in the link text

In an ASP.NET MVC view I'd like to include a link of the form:
Link text <span>with further descriptive text</span>
Trying to include the <span> element in the linkText field of a call to Html.ActionLink() ends up with it being encoded (as would be expected).
Are there any recommended ways of achieving this?
You could use Url.Action to build the link for you:
link text <span>with further blablah</span>
or use Html.BuildUrlFromExpression:
text <span>text</span>
if you like using Razor, this should work:
link text <span>with further blablah</span>
Another option is to render your action link to an MvcHtmlString as per normal, using either HTML.ActionLink, or Ajax.ActionLink (depending on your context), then write a class that takes the rendered MvcHtmlString and hacks your html link text directly into the already rendered MvcHtmlString, and returns another MvcHtmlString.
So this is the class that does that: [please note that the insertion/substitution code is VERY simple, and you may need to beef it up to handle more nested html]
namespace Bonk.Framework
{
public class CustomHTML
{
static public MvcHtmlString AddLinkText(MvcHtmlString htmlString, string linkText)
{
string raw = htmlString.ToString();
string left = raw.Substring(0, raw.IndexOf(">") + 1);
string right = raw.Substring(raw.LastIndexOf("<"));
string composed = left + linkText + right;
return new MvcHtmlString(composed);
}
}
}
And then you would use it in the view like this:
#Bonk.Framework.CustomHTML.AddLinkText(Ajax.ActionLink("text to be replaced", "DeleteNotificationCorporateRecipient"), #"Link text <span>with further descriptive text</span>")
This approach has the advantage of not having to reproduce/understand the tag-rendering process.

Resources