Parse Html string with Razor - asp.net-mvc

I have an application which generates dynamic html code with asp.net core tag helpers like
<input type="hidden" asp-for="Id" />
<input asp-for="Name" />
<input asp-for="IsActive" />
I return this html code from the database into the controller, I need to parse it with Razor Engine of asp.net core and of course pass a model for the engine to get data from, How can I do that?

A possible way to solve this, is by creating a custom IFileProvider that access the database.
Here is a blog post that explains how, but it's a bit older:
https://www.mikesdotnetting.com/article/301/loading-asp-net-core-mvc-views-from-a-database-or-other-location
The current offical FileProvider docs are here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-2.2
This would simulate a virtual file-system with the content from the database, those views can then be used like any cshtml file (e.g. as partial view)

I ended up creating a custom file provider which get the views from the database and this link explains it
https://www.mikesdotnetting.com/article/301/loading-asp-net-core-mvc-views-from-a-database-or-other-location

Define a model
public class Model {
Id, Name...
}
and
#Html.Raw(your html template)

Related

Is there any way to create a custom MVC Razor element like "text"?

I want to create a custom razor tag like <text></text> to decide what to do with the html code inside of it. Is there any way to create razor elements like <text></text> element and add it to the razor engine?
I don't want to create any HtmlHelpers for this.
For Examle:
<WYSYWIG>
Hello There!
</WYSYWIG>
or
<WeatherChart City="NY">
</WeatherChart>
Explanation:
Well the idea is to have server tags to be translated (Parsed) to html codes by the attributes given to them. This kind of codes helps junior developers not to be involved with the complexity of controls.
The closest thing to what you are describing is to create display or editor templates. You can then define a template for a model and use it with #Html.DisplayFor() in the view.
Here is a good blog post to get you started aspnet mvc display and editor templates and a quick overview of the structure below.
Example
Model - WeatherChartModel.cs
public class WeatherChartModel
{
}
Display template - WeatherChart.cshtml
<div class="weather-chart">
// Some other stuff here
</div>
View - Index.cshtml
#model WeatherChartModel
#Html.DisplayForModel() // This will output the template view for the model
In order to create custom element handling in razor, such as <text>, you'd need to implement a custom System.Web.Razor.dll (which is responsible for parsing the document). Specifically, the class you're looking to re-implement would be the System.Web.Razor.Parser.HtmlMarkupParser.
However, I don't believe this is necessary given how flexible the framework itself is. If you're looking to keep things modular, have a look at either using DisplayTemplates/EditorTemplates or consider writing your own extension method. For example, either of the following would be more ideal:
#* TextField is decorated with UIHint("WYSIWYG"), therefore
calling ~/Views/Shared/EditorTemplates/WYSIWYG.cshtml *#
#Html.EditorFor(x => x.TextField)
#* WeatherField is decorated with UIHint("WeatherChart"), therefore
calling ~/Views/Shared/DisplayTemplates/WeatherChart.cshtml *#
#Html.DisplayFor(x => x.WeatherField)
Alternatively:
#* Custom extension method *#
#Html.WysiwygFor(x => x.TextField)
#* Another custom extension method *#
#Html.WeatherChartFor(x => x.WeatherField)

Inconsistent null attribute handling in ASP.NET MVC 4

I have been trying to handle optional HTML required and readonly attributes in ASP.NET MVC 4. For my surprise, I found out that null attributes in HTML helpers are rendered as empty strings while they are removed completely in Razor (desired behavior).
For example, this code:
#{ string disabled = null; string #readonly = null; }
#Html.TextBox("t1", "Value", new { disabled, #readonly })
<input type="text" name="t2" value="Value" disabled="#disabled" readonly="#(#readonly)" />
Renders:
<input disabled="" id="t1" name="Txt1" readonly="" type="text" value="Value" />
<input type="text" name="t2" value="Value" />
Basically what I want to know is:
What is the reason behind these two different behaviors?
Is there a way to get the same result using Html.TexBox without writing any custom code?
EDIT
This is not possible without writing a custom Html Helper, but there's a feature request for this on CodePlex.
The Html.TextBox() behavior comes from code in System.Web.Mvc.Html that transforms a RouteValueDictionary of attributes into actual HTML. (I believe that code is in TagBuilder)
The raw HTML tag behavior comes from a feature in the Razor v2 language parser that removes attributes in Razor markup that resolve to null at runtime.

Bring ASP.NET MVC Model Binding to ASP.NET WebForm

In ASP.NET MVC, on [HttpPost] methods, the MVC runtime will automatically maps and transfers the data from the form fields in the front end into a View Model, based on field names.
How can I accomplish the same thing in ASP.NET WebForm?
e.g. I have an object called Person with FirstName and LastName properties.
I have a WebForm page with Textbox controls with FirstName and LastName respectively.
When pressing Submit on the form, is there a way to automatically bind FirstName and LastName to the Person object in the code-behind Button_Click event?
ASP.net 4.5 is actually going to have built in Web Forms model binding.
The Gu has a post on it and a few other things here...
http://weblogs.asp.net/scottgu/archive/2011/09/05/web-forms-model-binding-part-1-selecting-data-asp-net-vnext-series.aspx
You can do this in webforms v4.5 using model binding. It's a way we call as Ad-Hoc Model Binding where you can bind to controls without using data bound controls such as formview. I plan to blog about it but following code describes the blog in short
The following is how your markup will look.
My model has 2 properties: name and description
Name<input type="text" name="Name" value=" " id="Name" />
<br />
Description<input type="text" name="Description" value=" " id="Description" />
<br />
<asp:Button Text="Submit" runat="server" OnClick="Unnamed_Click" />
The following is the code in the button click handler.
category is my model. In this case the model binding system pulls in the value from the form value provider which looks in the form collection.
var category = new Category();
var formValueProvider = new FormValueProvider(ModelBindingExecutionContext);
TryUpdateModel(category, formValueProvider);
if (ModelState.IsValid)
{
// save changes to database
}
Perhaps the easiest way is to assign the values explicitly in the Page_Load event, whenever it is a postback. Something like this:
if (this.IsPostBack)
{
person.FirstName = FirstNameTextBox.Text;
person.LastName = LastNameTextBox.Text;
}
Or were you looking for a more declarative approach?
Take a look at Model Binder for ASP.NET Web Forms. It is doing what you want - maps postback data to class via custom attributes applied to its properties.

In Grails GSP, what is the equivalent to Spring MVC's <input name="entity.list[0].field">?

I'm coming from a Spring MVC background on a new Grails app. I have an object that contains a list of dependent objects. On the create and edit screen, I want to edit that object and its list of objects at the same time. In Spring MVC, you could use special names to bind the form fields to items in a list. Example:
Entity { String name, List items }
<form:input name="entity.items[0].value" value="${entity.items[0].value}"/>
I've tried similar variations in my GSP create and edit forms, but no luck.
I haven't used this with tag (is it a Java taglib?), but what you are doing is along the right path. I don't think you need the entity in there, the name should be just "items[0].value"
Here is some code I have that does what you need (using HTML input tag):
<input type="text" name="subItems[0].date"/>

performing searches with ASP.NET MVC

Ok, I've just started learning ASP.NET MVC after being an ASP.NET developer for awhile. I think my main problem I'm having is trying to "unlearn" ASP.NET when developing my MVC projects.
Here's my question: I have a page which has some input fields. These fields are parameters to a search I'm trying to run against a database. The user checks the boxes next to the types of items they want to see and then clicks "Search". Very simple stuff.
I'm having trouble wrapping my mind around how exactly to "postback" to the page to display the results. Is it better to use jQuery and serialize the form? Do I use my Entity Framework models I've created? What's the best way to go about
I'm really excited about MVC and the control it gives me, but I need to get over these initial obstacles if I ever want to "sell" it to my boss as the way to develop all of our web apps. Thanks for reading!
If you haven't already, consider taking a look at the NerdDinner Tutorial featured in Professional ASP.NET MVC 1.0 by Rob Conery, Scott Hanselman, Phil Haack, and Scott Guthrie. It contains a great demonstration of many of the features of ASP.NET MVC including performing a search and returning the data both through a full page post and also asynchronously using JSON.
If your inputs are inside html form element (different story if javascript is involved) - you can use default model binding (it binds route values and querystring parameters too).
<form ...>
<input type="text" name="query" />
<input type="submit" .../>
</form>
on submit it will automagically bind form values (by name) to action parameters:
public ActionResult PerformSearch(string query)
{
//whatever
}
In your case - i suspect you got inputs as checkboxes. Something like this should work:
<form...>
<input type="checkbox" name="p" value="value1" />
<input type="checkbox" name="p" value="value2" />
<input type="checkbox" name="p" value="value3" />
<input type="checkbox" name="p" value="value4" />
<input type="checkbox" name="p" value="value5" />
</form>
public ActionResult PerformSearch(string[] p)
{
//whatever
}
Only - if (form method == "GET"), URL won't look nicely. :)
To show results, make a model for your view in action and just show it through view:
public ActionResult PerformSearch(string[] p)
{
var model = _searchService(p);
return View("Results", model);
}
Views/Results.aspx
<% foreach(var bar in Model){ %>
<%= bar.Name %>
<%}%>
P.s. When considering AJAX calls, always remember that you are loosing ability to show URL + search engines don't understand JS.

Resources