Load html from returned string - html

I have the string and its returning function in the code-behind:
string xmlContents = "<ul><li>Installation<br /><ul><li>Startup</li><li>Getting there</li><li>Steps</li>" +
"<li>Pictures</li></ul></li><li>Usage<br /><ul><li>Tilbud pane</li><li>Report pane</li>" +
"</ul></li></ul>";
public String returnXml()
{
return xmlContents;
}
Then I call it in the aspx file:
<div id="treeviewMenu">
<%returnXml(); %>
</div>
When I simply write the html code (of the list) directly in the div - it's ok. But by passing the string - it doesn't work.
What am I doing wrong and how to fix it ?

Note: = sign whithout ; sign
Replace with this code:
<div id="treeviewMenu">
<%=returnXml() %>
</div

You can easily assign html to div by making div server accessible by adding runat="server"
HTML
<div id="treeviewMenu" runat="server"></div>
In code behind
treeviewMenu.InnerHTML = xmlContents;

Related

Why don't the String values get displayed as HTML tags using innerHTML?

I get string data from my database to my variable, I want to display them as HTML tags by [innerHTML], but it doesn't work.
The variable is displayed on string instead HTML Tags.
I tried to use with DomSanitizer but it don't work:
article:Article[];
(article.articlesTitleHtml:SafeHtml;)
in the function:
this.article.forEach(elementArticle => {
elementArticle.articlesTitleHtml = this.sanitizer.bypassSecurityTrustHtml(elementArticle.articleTitle)
});
in HTML page:
<div *ngFor="let item of articles">
<div id="{{item.articleId}}">
<h2 class="chart" [innerHTML]="item.articlesTitleHtml"></h2>
</div>
my code:
in Type Script:
articles:Article[];
ngOnInit() {
this.apiArticle.getArticleList().subscribe(data=>{
this.articles=data
})
in HTML page:
<div *ngFor="let item of articles">
<div id="{{item.articleId}}">
<h2 class="chart" [innerHTML]="item.articleTitle"></h2>
</div>
</div>
It should work, you can check here...
if you can share the type of data that you're dealing with, it will give more insight into the appropriate DomSanitizer method which should be called
in my example above, i used both bypassSecurityTrustHtml & bypassSecurityTrustUrl for the 2 different types of strings which needed sanitization

How to write code in html for retrieving the session value.?

I have a Default2.cs file which stores a value in session
TextBox1.Text = "Haii";
Session["name"] = TextBox1.Text;
and i need to retrieve it in an html page- Default.aspx
<script runat="server">
Sub Page_Load
string na=(string)Session["name"];
Label1.Text=na;
End Sub
</script>
it shows an error 'String' is a class type and cannot be used as an expression.
please help
Try this in HTML in Defaul.aspx,
<% string na=(string)Session["name"]; %>
<label id="Label1"><% =na %></label>
For ASPX Engine:
Enclose your code in <% Your Code here %>
<% string na=(string)Session["name"]; %>
For Razor Engine:
Enclose your code in #{ Your Code here }
#{
string na=(string)Session["name"];
}

Update HTML tag in the view with Ajax dilemma

I'm new to this and have no idea how it must work.
I have a partial view in a foreach in my view that lists all news comments for that news article.
I have a textarea with a post button where the user can submit further comments on this news article.
The new news article must be appended to the list, without doing a location.reload. I was told do use AJAX, not JSON.
Here's my controller:
[HttpGet]
[NoCache]
public ActionResult SetCommentOnNews(int newsId, string newsComment) ??
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.SetCommentOnNews(newsId, newsComment, currentUser.UserId);
return Json(new { success = true }, JsonRequestBehavior.AllowGet); ??
}
<div class="news-comment-content" id="news-comment-content">
<% if (Model.Results != null) {
foreach (var newsItem in Model.Results.NewsComments) %>
<% { %>
<% Html.RenderPartial("~/Views/Home/SetCommentOnNews.ascx", newsItem); %>
<% } %>
</div>
my partial:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Zinc.Web.Areas.News.ViewModels.Home.NewsCommentsViewModel>" %> //this also not right
<div class="news-post-list-item">
<div class="news-post-user-info-wrapper">
<div class="avatar">
<img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png"/>
</div>
<div class="who-and-when-box">
<%: newsItem.CommentDate %>
<br />
<br />
<%: ViewBag.UserName %>
</div>
<div class="news-comment"><%: newsItem.NewsComment %></div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="header">
<h3>
Leave a comment
</h3>
</div>
<div>
<textarea id="textareaforreply" rows="3" cols="160"></textarea>
</div>
<div>
Post
</div>
<script type="text/javascript">
function PostNewsComment(newsId) {
$("post-button").click(function () {
var jqxhr = $.getJSON("<%= //Url.Action("SetCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").text(), function (data) {
if (data.success) {
alert($("#textareaforreply").text());
$('#news-comment').append($("#textareaforreply").text());
}
});
}
</script>
The above JS is what I have and must inject HTML in to the list using AJAX?
I have NO idea how to do this. Can some one help please?
Thanks
To inject HTML into a list using AJAX I would use Knockoutjs with templates instead of partial views. Knockout can be used to render the information in the browser. Views are for rendering server side, which does not jibe well with AJAX.
What do you mean when you say, "I was told do use AJAX, not JSON". AJAX uses JSON as a method for serializing the data that is sent over the network. Are you referring to the JQuery methods ajax versus getJSON? getJSON is just a wrapper around the ajax method that configures it specifically to retrieve JSON using the HTTP GET verb. Either will work fine, but ajax does give you more control in configuring the request.

How to Get Model Data from Partial View?

I am creating a site in which I utilize partial views to display various bits of data about a single Model. Here is a bit of the HTML. (Note, all of these are contained within a single form and the Index page that these partials are rendered in is strongly typed to the main model. The main model contains various lists of data.)
<div id="tab1"><% Html.RenderPartial("Tab1", Model); %></div>
<div id="tab2"><% Html.RenderPartial("Tab2", Model.AnItemList1.FirstOrDefault<AnItemList1>()); %></div>
<div id="tab3"><% Html.RenderPartial("Tab3", Model.AnItemList2.FirstOrDefault()); %></div>
Here is ONE of the partial views headers (for 'tab2'):
<%# Language="C#" Inherits="System.Web.Mvc.ViewUserControl<AnItem1>" %>
The pages display correctly. The issue is that, when I enter data into the various parts of the partial pages and then submit the entire form (via POST), the data is not making it back to my data store (MSSQL) - but this only happens for any of the list items (that are contained within the Model). The first partial page does properly have its data set within the data store.
What am I doing wrong here? Should I only be passing the model to Html.RenderPartial and then get the specific model I need on the partial page? Should I pass the entire list and then get the first (right now, I only care about the first item in the list - that will EVENTUALLY change, but not any time soon).
Suggestions or thoughts appreciated.
Update: Here is how I accessing the properties on the partial views.
<div class="data-group">
<%: Html.CheckBoxFor(model => model.Property1) %>
<%: Html.LabelFor(model => model.Property1) %>
</div>
Update 2: Per request...
Controller Action (ScenarioController):
public ActionResult Index(int id = 0)
{
if (id == 0)
{
SavedScenario scenario = new SavedScenario();
scenario.AnItemList1.Add(new AnItem1());
scenario.AnItemList2.Add(new AnItem2());
return View("Index", scenario);
}
else
{
SavedScenario scenario = repository.GetScenario(id);
if (scenario == null)
return View("NotFound");
else
return View("Index", scenario);
}
}
[HttpPost]
public ActionResult Index(SavedScenario scenario)
{
if (ModelState.IsValid && TryUpdateModel(scenario, "SaveScenario"))
{
repository.Add(scenario);
repository.Save();
}
return View(scenario);
}
Rendered HTML (I can only include parts of it - this is a small sample of what is in the form):
<form action="/Scenario" id="form0" method="post">
<!-- This is the one that works - the basic Scenario. Top level. -->
<fieldset>
<legend>Scenario Information</legend>
<div class="data-group">
<div class="editor-label">
<label for="ScenarioName">Scenario Name</label>
</div>
<div class="option1">
<input class="wide" id="ScenarioName" name="ScenarioName" type="text" value="" />
</div>
<div class="validation">
<div><span class="field-validation-valid" id="ScenarioName_validationMessage"></span></div>
</div>
</div>
</fieldset>
<!-- This does not work or get submitted (as far as I can tell). -->
<div id="tab2">
<fieldset>
<legend>Tab2</legend>
<div class="data-group">
<input id="Property1" name="Property1" type="checkbox" value="true" /><input name="Property1" type="hidden" value="false" />
<label for="Property1" />
</div>
</div>
</fieldset>
</form>
My apologies for having to keep this so generic.
Hard to guess from this much code. However you should make sure that all properties of your models have the same prefix when they are posted back to the server
Edit: form field names should match property names of your model to correctly bind all values. You have two fields with the same name that you can bind in following way
[HttpPost]
public ActionResult Index(SavedScenario scenario, List<bool> Property1)
{
// here you can do with values coming in property1
if (ModelState.IsValid && TryUpdateModel(scenario, "SaveScenario"))
{
repository.Add(scenario);
repository.Save();
}
return View(scenario);
}
It might be issue with naming the fields on your partial forms. Try naming the fields on your partial views by prefixing it with the name of the Model passed into it...like 'AnItemList1.name' instead of just 'name'..I am just guessing here though...but that's what I did sometimes to fix the problem when I was getting values as null..

How do I a embed a variable css style in a VB.NET xml string literal?

I would like to add a variable data to a string literal WITHIN the HTML tag
Dim locationOfImage as string = "http://blahblah......"
Dim xmlString = _
<div style="background:url(" <%= locationOfImage %> ")">
<h3>Some text</h3>
</div>
The above does not work, I can't quickly determine how to do this? Is this possible. I could achieve what I am attempting to do with a StringBuilder but want to use the xml literal if possible.
<div style="<%= String.Format("background:url('{0}')", locationOfImage) %>">