Replacing string with HTML control MVC View - asp.net-mvc

<td style="font-size:1em;font-family:Verdana;color:darkkhaki">
#item.ObjQuestions.QuestionText.Replace("____", "<input type='Text'></input>")
</td>
I have seen a lot of similar questions, but I guess this is not a duplicate, because all the questions are how to add a control on serve-side. I want to replace a string that I get in my object.property in my cshtml View. I want to inject a textbox (or any html control) in place of some special characters.
The above code snippet simply replaces <input type='Text'></input> as text.
For e.g.
Acronym of CSS is ##
Here ## should be replaced by a textbox.

MVC will by default HTML encode all your strings in your view. You have tell it to output it as a raw HTML string instead by using Html.Raw:
#Html.Raw(item.ObjQuestions.QuestionText.Replace("____", "<input type='Text'></input>"))

Another option without having to use Html.Raw (security concern) is to split the string by the replacement word then combine them together with the HTML input:
#
{
string[] splits = item.ObjQuestions.QuestionText.Split(new string[] {"____"}, StringSplitOption.None);
}
#splits[0]
<input type='Text'></input>
#if (splits.Length > 1)
{
#: #splits[1]
}
This is for string with one placeholder only, if otherwise use a loop instead.

Related

How to return a filename when user clicks button in Thymeleaf?

This is a crude way to do it BUT I'm trying to get this
model attribute "file" into the PostMapping "getfile" so that when the user clicks "Submit", they are directed to the file associated with that button.
I've seen many webpages telling me th:value will insert the desired text into the form field... it's not working for me.
In the end, I'm just trying to send the user to the file they click on.
Template:
<table>
<tr><th>File Name</th>
</tr>
<tr th:each="file : ${filedata}">
<td>
<form action="#" th:action="#{~/home/ebay/getfile}" method="post" th:object="${filetobind}">
<!-- th:field maps to object -->
<input type="text" th:field="*{fileName}" th:value="#{file.fileName}" th:text="${file.fileName}"/>
<input type="submit" value="Get" />
</form>
</td>
</tr>
</table>
Controller:
#GetMapping(Mappings.FILES)
public String getDirectory(Model model){
model.addAttribute(AttributeNames.FILE_DATA, fileService.getDirectory());
model.addAttribute(AttributeNames.FILE, new DirectoryFile());
// debug
System.out.println("#############################################################");
for(DirectoryFile file : fileService.getDirectory()){
System.out.println(file.getFilePath());
}
System.out.println("#############################################################");
return ViewNames.DIRECTORY;
}
#PostMapping("getfile")
public String getFile(Model model, #ModelAttribute(AttributeNames.FILE) DirectoryFile file ){
System.out.println("Filepath:" + file.getFileName());
//model.addAttribute(AttributeNames.FILE, file.getFileName().trim());
return "data/" + file.getFileName();
}
Let's have a look at your input
<input type="text" th:field="*{fileName}" th:value="#{file.fileName}" th:text="${file.fileName}"/>
On form submission, you are sending the controller the value of your input in an attribute called "fileName" inside your object "filetobind", this happens because of how you defined th:field and the form th:object, and it's fine.
Now, for the th:value part and why it isn't working for you: The syntax #{...} is for externalizing text literals in files so you make your html more "generic", quoting from the documentation:
Externalizing text is extracting fragments of template code out of
template files so that they can be kept in specific separate files
(typically .properties files) and that they can be easily substituted
by equivalent texts written in other languages (a process called
internationalization or simply i18n). Externalized fragments of text
are usually called “messages”.
Messages have always a key that identifies them, and Thymeleaf allows
you to specify that a text should correspond to a specific message
with the #{...} syntax
So those are good for labels, for example, but not input contents (input values).
Now since it is a text input, you can either ommit the th:value part and let the user fill the input, or you can give it a value with the syntax ${...}, which access a variable passed from the controller. Quoting the doc:
The ${today} expression simply means “get the variable called today”,
but these expressions could be more complex (like ${user.name} for
“get the variable called user, and call its getName() method”).
Change the value for th:value="${file.fileName}" and you should be fine (as long as you provide the file variable from the controller).

Passing html object properties into embedded ruby code

How can I pass html object properties into embedded ruby code in an html.erb file?
Lets say I have a ruby method A that accepts a string parameter(and also the return value of A is string). I think of scenarios like the following:
<input type="text" id="t" value="Leaves">
<%= A(document.getElementById("t").value) %>
Obviously I can't write code that way.
I want to pass the value/text of the textbox into method A and print A's return value into the html body. How can I do that?
Also, if I want to continuously check the value of the textbox and append A's return value(when passed the current value of the textbox to A) to the body of the document, what should I do? And if I instead wanted to set some paragraph p's text to this return value, what should I have done?
You can use a HTML parser like Nokogiri.
frag = Nokogiri::HTML.fragment('<input type="text" id="t" value="Leaves">')
frag.at_css('#t').attr('value')
But it seems like a rather silly and overcomplicated solution to something that most likely can be solved by not using HTML strings to pass around data in your views / helpers in the first place.

How to use a razor variable mixed with html ID text?

I am getting an error because the razor and html is getting confused by the compiler I imagine.
<div id="#Model.MyLabelCars" ...>
My model variable is:
Model.MyLabel
The "Cars" is just raw text that should be in the HTML.
So say Model.MyLabel's value is "123" the ID should be:
id="123Car"
How can I seperate the model's variable name and HTML?
You could use regular string add operator
<div id="#(Model.MyLabel + "Car")"></div>
Or C# 6's string interpolation.
<div id="#($"{Model.MyLabel}Car")"></div>
What you want is to use the <text></text> pseudo tags
<div id="#Model.MyLabel<text>Cars</text>" ...>

Thymeleaf would not resolve html entities

How do I get thymeleaf to resolve my html entities?
I have the following:
<input th:name="title" th:value="Wayne’s World" />
will simply produce an input element with "Wayne’s World" instead of "Wayne's world".
Any way to make thymeleaf resolve the html entities?
You have two choices.
First. Do not use html entities at all. Just escape special symbols using \. Note, that you have specify string value in single quotes:
<input th:name="title" th:value="'Wayne\'s World'" />
Second. Use Thymeleaf's string utility for escape xml enitites:
<input th:name="title" th:value="${#strings.escapeXml('Wayne’s World')}" />
When your string value is coming from controller, don't use __${}__ preprocess expression. It doesn't needed. Just use Thymeleaf's standard variable expression ${}. And don't enclose this expression in single quotes. Look at ${title} variable in next example:
<th:block th:include="row::row(attrs='value=${title}, minLength=\'.{1, 16}\', required=true, ... />
In this case you can add string value in controller as is, without any escaping:
public String method(ModelMap model){
...
mode.addAttribute("title", "Wayne's world");
...
}

What does #: mean in ASP.net MVC Razor?

I'm working on an ASP.net MVC Razor view that someone else wrote. I see that it contains the following:
<span>
#:
</span>
I know that the # symbol allows me to insert code into a view, but what does #: stand for?
In MVC, # is the respective char that allows you to use razor inside HTML (inside a .cshtml) which in runtime (or precompiled) will be converted to c#.
With # you may write C# within HTML and with #: you may write HTML within C#.
Example:
#foreach (TestClass item in Model)
{
#:#item.Code - #item.Name
}
Without the #: it wouldn't be possible to do this, since all the chars after the first # will be considered as C#.
This way you are saying that you are getting the two variables from item and placing the char - between them and the result is a content block (or html/text)

Resources