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")
Related
I have an ASP.NET MVC application that I need to add content management pages to. Since it's CMS the path of the pages are going to be variable. I am trying to figure out how to get ASP.NET to display a view that is variable. What does the controller look like?
The code would be something like this:
Dim MyView As New System.Web.Mvc.ViewResult()
Return MyView
But that doesn't let me define the content of the view, which I'm not sure how to do. The view does not physically exist; I need to dynamically generate it from data within my database. I am storing the HTML in the database.
You can create your content "by hand", without Razor views and return Content with the generated HTML instead of View in your action method.
EDIT:
Or, create a master view with all the common elements that accepts generated content as a string:
#model string
<html>
<!-- all the common stuff here -->
#Html.Raw(Model)
<!-- more common stuff -->
</html>
Your controllers would generate the HTML and pass it to this view:
public ActionResult Index()
{
var html = GenerateContent(); // or whatever
return ActionResult("MasterView", (object)html);
}
It's important to cast the second parameter to an object as otherwise it would be interpreted as layout location.
If you need to insert the generated content between common components you can pass a dictionary of strings as a model and render just the part you like, eg. Html.Raw(Model["footer"])
What does the controller look like?
public ActionResult Index()
{
string dynamicViewName = "~/Views/Shared/FooBar.cshtml";
return View(dynamicViewName);
}
You could also specify a Layout if you wish:
public ActionResult Index()
{
string dynamicViewName = "~/Views/Shared/FooBar.cshtml";
string dynamicLayout = "~/Views/Shared/_SomeLayout.cshtml";
return View(dynamicViewName, dynamicLayout);
}
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 :)
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?
I've got an MVC application with basic view:
myapp.com/category
and a switcher to second one:
myapp.com/category/list
App is used as independent one and as also in other application into iframe where src is: myapp.com/category. I want do not show page header when it is used into iframe, how can I achieve it? I was trying to add querystring, myapp.com/category?show=false, and set this as iframe src, but when I switch to the second view the parameter is not passed.
You could create a helper method to construct URLs that would keep the show parameter in place. For example:
public static string GetModifiedUrl(this UrlHelper helper, string url)
{
string qstring = helper.RequestContext.HttpContext.Request.QueryString["show"];
if (!string.IsNullOrEmpty(qstring)) url += "?show=" + qstring;
return url;
}
Then in the views, for example:
<a href='#Url.GetModifiedUrl(Url.Action("Index", "Home"))'>Home</a>
Another option is to create add a value to the session on the first request, and use that instead. Ie, put some logic in the controller like this:
var qs = Request.QueryString["show"];
if (!string.IsNullOrEmpty(qs))
{
Session["show"] = qs;
}
Then in the views, use #Session["show"] instead of #Request.QueryString["show"] to decide whether you show the header.
Break the main view into two partial views.
Then, when calling for the master/external app, call the partial view that has just the content.
When calling the regular native app, call a VIEW that contains both the partial views (header as well as content).
I have a partial view that I want to be generic. According to this question, partial views cannot be generic. So I instead made an HtmlHelper extension that handles the pieces for which I want type-safety, then hands off the rest to a real partial view.
Usually my helper is called on page load, which works fine, but sometimes I want to add a row or something through AJAX. When this happens, the controller cannot use my "partial view" since it does not have access to the HtmlHelper.
Apart from having a partial view with a model of type object, is there anything I can do?
I'm using Razor, if that is important.
A simplified version of what I'm doing:
public static MvcHtmlString DoStuff<T>(this HtmlHelper html, IEnumerable<T> data,
Func<T, ViewModelType> StronglyTypedFn, string PartialName)
{
// the pre- and post-processing for the partial view is complex enough I'd like
// to encapsulate it. But I want the encapsulation to include the safety
// benefits that generics give.
var mappedData = data.Select(StronglyTypedFn);
string htmlData = "";
foreach(var model in mappedData){
htmlData += html.Partial(PartialName, model);
}
htmlData += "some boilerplate footer html";
return htmlData;
}
I realize that in this example I have so few lines of code outside the partial view that it seems pointless to have a helper, but in my real example it is more complex.
Now, in an ajax call I want to return Html.DoStuff(). But I can't, because this requires access to the HtmlHelper, and the helper isn't available inside a controller.
You could just have a simple action method that calls the partial for one model instance
public PartialViewResult Single(string partialName) {
return PartialView(partialName);
}
You could use a View with a Dynamic type instead of object.
But... It seems as if there's some misunderstanding here because the Controller shouldn't try to render the view at all. Could you post the Controller code?
The better option is, IMO, returning a JsonResult for your ajax request and adding the row/rows on client side using JS.