How use ViewBag to display data - asp.net

SchoolController
schoolBLL content = new schoolBLL ();
DatabaseSchool dbSchool = content.GetSchoolInfoById(LoginStaffId);
if (dbschool != null)
{
string textcontent = dbschool .text_content;
}
class file
public DatabaseSchool GetSchoolInfoById(int StaffId)
{
return SchoolRepo.Find(a => a.schoolcontent_id == StaffId).FirstOrDefault();
}
So, I am trying to display the data in to a HTML page with this tag
How can I pass the value from the controller into the HTML page ?
I already tried to use ViewBag and it doesn't work!

For displaying data into an html page try below:
School Controller:
schoolBLL content = new schoolBL();
DatabaseSchool dbSchool = content.GetSchoolInfoById(LoginStaffId);
if(dbschool != null)
{
TempData["textcontent"] = dbschool.text_content;
}
HTML:
<textarea id="txtcontent" class="form-control" rows="20">#TempData["textcontent"]</textarea>
Better to use CSHTML:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
#Html.TextArea("Content", TempData["textcontent"])
</body>
</html>

Related

Blazor set CSS file based on request path

I'm attempting to switch out the css file on the fly - based on which part of the web-system the user is in (i.e. if the user is on mydomain/students/page then the page loads with students.min.css, rather than site.min.css).
I've tried doing it within the _Host.cshtml:
#page "/"
#namespace FIS2withSyncfusion.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
//sniff the requst path and switch the stylesheet accordingly
string path = Request.Path;
string css = "site.min.css";
if (path.ToLowerInvariant().StartsWith("/students"))
{
css = "students.min.css";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Martin's Blazor Testing Site</title>
<base href="~/" />
<link rel="stylesheet" href="css/#(css)" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
<script type="text/javascript">
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob) {
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<script src="_framework/blazor.server.js"></script>
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
</body>
</html>
However, it doesn't seem to hit this codeblock after the first load of the site; meaning whichever page they first landed on denotes the stylesheet for the entire site.
Do I have to put this codeblock on every page or is there another way of doing this?
another way you could approach this is to create components that respond to different styling that you desire. From there you have two options:
Create dedicated css associate with the component. From the docs
Create a class toggle in the code block of the component, similar to how the NavMenu works.
After further experimentation, I've found that adding this block:
#{
//sniff the requst path and switch the stylesheet accordingly
string path = navManager.Uri;
Uri uri = new Uri(path);
List<string> parts = uri.Segments.ToList();
string module = parts[1].ToLowerInvariant().Trim('/');
string css = "site.min.css";
if (module == "students")
{
css = "students.min.css";
}
}
<head>
<link rel="stylesheet" href="css/#(css)" />
</head>
To the top of MainLayout.razor works perfectly - so long as you remove the equivalent block from _Host.cshtml

How to pass a map in thymeleaf (spring 4)

I want to pass a map from a properties file using the thymeleaf template engine.
Exception:
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'title' cannot be found on object of type 'java.lang.String' - maybe not public?
provider.html:
<!DOCTYPE>
<html th:include="receiver :: receiver(#{site})"></html>
receiver.html:
<!DOCTYPE HTML>
<html th:fragment="receiver(map)">
<head>
<title th:text="${map.title}">title</title>
</head>
<body th:text="${map.body}">
body
</body>
</html>
messages.properties:
site.title = Any title
site.body = Any body
Controller:
#Controller
public class StartController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String start(Model model) {
return "provider";
}
}
It simply like in Java. Key and value of the Map
<div th:each="userEnrty: ${userMap}">
<p th:text="${userEntry.key}">No Id!</p>
<p th:text="${userEntry.value}">No Name!</p>
</div>
So I figured out that property-files are processed as Map. So 'site' wasn't a map at all.
My solution now is to pass the name of the variable-prefi and get the keys by thymeleaf preprocessing.
provider.html:
<!DOCTYPE>
<html th:include="receiver :: receiver('site')"></html>
receiver.html:
<!DOCTYPE HTML>
<html th:fragment="receiver(mapname)">
<head>
<title th:text="#{__${mapname}__.title}">title</title>
</head>
<body th:text="#{__${mapname}__.body}">
body
</body>
</html>
messages.properties
site.title = Any title
site.body = Any body

Why does this var REQUEST ["name"] method always return null?

I'm self-learning how to create a form, pass the responses to a separate handler, and email them to my website account. I have the form, which works, and oddly enough, I have the mail portion working. However, this example is almost straight out of some ASP.NET help pages at Microsoft - yet it does not work, and I can't seem to find out why. What's wrong and how should it read instead?
Here's some form code:
{
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="Mailform.cshtml" enctype="text/plain"
method="post" name="formcontent">
<ul>
<li>
<label for="name" class="heavyred">Contact Name: &nbsp</label>
<input type="text" name="contact" autofocus="true" size="40"
required="" /><span class="tinyfont">&nbsp red denotes a
required field</span>
<span class="italicfont"style="margin-left: 22%"><br>Person
overseeing site development</span>
</li>
<li>
<label for="strngweak">List strengths:<br></label>
<textarea name="strngweak" placeholder="420 chars max"
cols="60" rows="7"></textarea>
</li>
</ul>
<div>
<input class="hyper buttn" style="margin-right:1%; font-size: 1em;
"type="submit" value="SUBMIT">
</div>
</form>
</body>
}
handler.cshtml code: (the first two requests end up NULL instead of getting data by name)
{
#{
var contact = Request ["contact"]; <----- NULL instead of name=contact data
var stweak = Request ["strngweak"]; <----- NULL instead of name=strngweak data
var from = "info#portalmagician.com";
var to = "sirrobcop#yahoo.com";
var subject = "I WANT A WEBSITE";
var msg = "From: ";
var errorMessage = "";
var debuggingFlag = true;
msg += contact + " Strengths: " + stweak;
}
{ try-catch block initializes webmail helper and sends email here }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
#if (IsPost) {
if (errorMessage == "") {<p>Your message has been sent!</p>;}
else {<p>Unable to send due server down or bad server info.</p>;}
}
</body>
}
Modify the enctype of your form to application/x-www-form-urlencoded (or delete it).

Durandal MVC 4 separate layout/mastepage for login ?

I am using MVC 4 Hot towel template, i have solved it MVC way right now, where i have _viewStart.cshtml:
#{
if (User.Identity.IsAuthenticated)
{
Layout = "~/Views/Shared/_Layout.cshtml";
Page.Title = "Home1";
}
else
{
Layout = "~/Views/Shared/_loginLayout.cshtml";
Page.Title = "Home2";
}}
and in the index.cshtml:
#using System.Web
#using System.Web.Optimization
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="text/javascript">
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
var mq = "##-ms-viewport{width:auto!important}";
msViewportStyle.appendChild(document.createTextNode(mq));
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
</script>
#if (#User.Identity.IsAuthenticated)
{
<div id="applicationHost">
#Html.Partial("_splash")
</div>
#Scripts.Render("~/scripts/vendor");
if(HttpContext.Current.IsDebuggingEnabled) {
#Html.AntiForgeryToken()
<script>
window.userId = "#User.Identity.Name";
console.log(window.userId);
</script>
<script type="text/javascript" src="~/App/durandal/amd/require.js" data-main="#Url.Content("~/App/main")"></script>
} else {
<!-- Remember to run the Durandal optimizer.exe to create the main-built.js -->
<script type="text/javascript" src="~/App/main-built.js"></script>
}
}
else
{
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<div id="login">
<p>hello world</p>
</div>
}
Ive created a separate viewmodel user for login:
define(['services/logger'], function (logger) {
var vm = {
activate: activate(),
userName: ko.observable(),
password: ko.observable()
};
return vm;
//#region Internal Methods
function activate() {
logger.log('login View Activated', null, 'login', true);
return true;
}
//#endregion
});
and created login view:
<section>
<h2>My login model without content yet</h2>
</section>
(i know i am not using viewmodel in this view, but its only for test)
How do i do same functionality in Durandal? and is it even possible?
No hate, i am new to Single page application and durandal + breeze.js + knockout.
I would suggest using the built in ASP.net authentication / login mechanisms - ie <authentication> in web.config.
I found https://github.com/jamesc88/Durandal_Serverside_Authentication useful.

Error deleting last value from a custom URL

I am currently creating a page that is accessed via the custom url functionality.
I am trying to delete all components in a multivalue field. I get a Cannot delete a value as an error when deleting the last one.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" language="javascript" src="/WebUI/Core/Controls/Popup/PopupInit.js"></script>
<script type="text/javascript" language="javascript">
function removeAllValues() {
var fields = window.dialogArguments.getFields();
if (fields != null) {
for (var i = 0; i < fields.length; i++) {
window.dialogArguments.container.deleteField(fields[i]);
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" onclick="removeAllValues();" value="Delete All" />
</div>
</form>
</body>
</html>
Is there any documentation other than two brief pages on the LiveContent site?
You could also change your function a little bit to delete all fields except the last one and then set the last fields value to nothing:
function removeAllValues() {
var fields = window.dialogArguments.getFields();
if (fields != null) {
var lastFieldIndex = fields.length - 1;
for (var i = 0; i < lastFieldIndex; i++) {
window.dialogArguments.container.deleteField(fields[i]);
}
fields[lastFieldIndex].setValues([]);
}
}

Resources