ViewBag does not show new line [closed] - asp.net-mvc

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I want to show text on two separate lines for the page header:
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Message</h1>
</hgroup>
</div>
</section>
}
I have the following code in controller:
public ActionResult Login(string returnUrl)
{
StringBuilder sb = new StringBuilder();
sb.Append("Web Security Administration Portal");
sb.AppendLine();
sb.AppendLine();
sb.Append("Services, Inc. - SSOAdmin v2.00");
ViewBag.ReturnUrl = returnUrl;
ViewBag.Message = sb.ToString();
return View();
}
ViewBag does not show new line. When viewing source code of generated html, looks like that two strings are on separated lines, but when page is rendered, lines are not separated.
I tried to use sb.Append(Environment.NewLine) and sb.Append(Text{0}, Environment.NewLIne) as well. Does not help here.
What can be wrong here?

Environment.NewLine puts the text on multiple lines in the HTML that is created. However, white space such as new lines are ignored by most HTML elements. You should add <br /> where you want new lines.
Alternately, you could change that behavior by adding see to the enclosing element that adds:
white-space: pre-wrap;
The best bet to get that to work would be to have your ViewBag be wrapped in a <p>.

Related

Conditional statements using vue.js with html element

Im new to vue.js, and Im trying to do a simple if with a date field within my ASP.NET MVC project.
I've seen examples on vue tutorials where the condition is done in the js file, but Im not convinced that this would help me.
I currently have a date field in my ViewModel that has two drop downs. This is for an application form that asks a person how long have they lived at their address. They can select up to 11 months and 6+ years. I have a button that allows them to add another address. When you click this button, the viewModel for the date fields are repeated so they can add another one (stored in a List).
However I want to wrap this around a condition that says only if the date entered is less than 6 years then the button would appear. Like I said, at the min it is there always.
my code for the address and its button is:
<fieldset>
<legend>Please provide all your addresses in the last 6 years</legend>
#Html.EditorFor(m => m.PreviousAddresses)
</fieldset>
<button class="button">Add another previous address</button>
What im trying to do is something like v-if="PreviousAddress < 6" but I dont think thats right. Can someone help with the syntax?
EDIT: The validation works on the back end. Just need the client side to work with it:
[Minimum(72, ErrorMessage = "Please enter 6 years address history")]
public int TotalAddressHistoryInMonths
{
get
{
int totalMonths = CurrentAddress?.Duration?.TotalPeriodInMonths ?? 0;
if (PreviousAddresses != null)
{
foreach (ResidencyInputViewModel residency in PreviousAddresses)
{
totalMonths += residency?.Duration?.TotalPeriodInMonths ?? 0;
}
}
return totalMonths;
}
}
The solution you have appears to be correct, but can you post the rest of your code. Seeing the data object should help.

What should be the standard coding pattern for Sitecore

Using Sitecore 8.0, MVC, VS2015
I managed to generate the footer content as desired, for a practice site, but would like to know the standard way of doing things. The question is simple, but tried to explain in detail. Please bear with that :)
Requirement: The footer should display Office addresses and they should be editable by the Content author.
Sitecore Template : Location, Telephone 1, Telephone 2, IsActive(type-checkbox).
Datasource : A folder with items of the above template.
Code:
public class FooterViewModel
{
public List<Sitecore.Data.Items.Item> Addresses { get; set; }
}
public class FooterController : Controller
{
public ActionResult Footer()
{
var datasource = RenderingContext.Current.Rendering.Item;
FooterViewModel viewModel = new FooterViewModel();
viewModel.Addresses = new List<Item>();
if(datasource != null && datasource.HasChildren && datasource.Children.Count > 0)
{
foreach(Item address in datasource.Children)
{
if (address["IsActive"] == "1")
viewModel.Addresses.Add(address);
}
}
return View("~/Views/Shared/Footer.cshtml", viewModel);
}
}
Rendering the html using a Sitecore Controller Rendering
cshtml:
#using Sitecore.Mvc
#using Sitecore.Mvc.Presentation
#model Democore.Models.FooterViewModel
<div>
#foreach (var address in Model.Addresses)
{
<div>
<h3>#Html.Sitecore().Field("Location", address)</h3>
<ul>
<li>
#Html.Sitecore().Field("Telephone 1", address)
</li>
<li>
#Html.Sitecore().Field("Telephone 2", address)
</li>
</ul>
</div>
}
</div>
<div>
<p>&copy Copyright #DateTime.Now.Year. All rights reserved</p>
</div>
Here are my questions. (..well all 3 are more or less similar)
How to better this code/structure (or) in which case might it fail.
I did not like the way I hardcoded the field names in controller &
cshtml. What if the author changes the field names. How to tackle
that.
How does it work in a real scenario, say for eg if author
wants to show a third phone number. Will they contact the developer?
Because that requires a change in design & code too right?
This is a very broad question and will probably get closed -but here are some tips!
You controller is fine as far as error handling goes. You really want to add a global error handler for your site. This is a good example of that: http://www.sitecorenutsbolts.net/2015/10/23/Rendering-Exception-Handling-The-Right-Way/
You have 2 options - use constants and field ID's not the names, not a great option but works. A better option would be to use an ORM/Wrapper to do that. Two good ones are Fortis and Glass Mapper - both are very good - I contribute to Fortis so that would be my recomendation.
Normally if the design of the component changes it will require development support. You could use something like BrainJock's Score or ZenGarden to build your site and then the editor has a lot more control. But still likely would need a developer.
Hope this helps. For some info on good Sitecore architecture look here: Sitecore Helix and Sitecore Habitat

creating dynamic id for divs in MVC with Razor... with a twist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The twist being, all answers that I found on the topic simply do not seem to work. I tried just about all formattings I found in answers to this question and made a few desperate attempts on my own, but none of them have any effect. It's almost as if razor wasn't there, but other razor synthax in the same cshtml file executes without trouble.
As most of the time, the div is declared in a loop and its name should be appended by i. Here's some things I tried, not in the order I tried them in. The order can be deduced by the decreasing sanity of the synthax:
<div id="accord#(i)">
<div id="#("accord" + i)>
<div id="#{#("accord" + i)}">
with:
string fName = "accord" + i; //fName is filled correctly, that much I could verify
I tried some things:
<div id=#fName>
<div id="#fName">
<div id="#(fName)">
<div id="#{fName}">
<div id=#(fName)>
<div id="#{#fName}">
<div id=#{#fName}>
I also tried several combinations of the two approaches, like for example
string fName = "accord";
<div id="#(fName + i)">
aso...
All of these attempts have not yielded any results... the id of the div is ALWAYS #Literaly_Whatever_Comes_after_=
So... can anybody venture a guess at what I'm doing wrong?
In the interest of completion, since you never know what might be involved, here's the entire loop. It doesn't have any actual logic in it, that comes after I made the concept work:
<div id="yearaccord">
#for (int i = 0; i < 4; ++i)
{
//add a nested months accordion for every year
<h3>i = #i</h3>
string fName = "accord" + i;
<div id="#{#fName}">
#for (int j = 0; j < 4; ++j)
{
//add an accordion displaying the blog titles for each month
<h3>j = #j</h3>
<div>
#for (int w = 0; w < 6; ++w)
{
//add blog titles
<h4>JabbadaJba #w</h4>
}
</div>
}
</div>
}
</div>
Note that ALL other razor synthax in this loop behaves the way I expected it to... only when it's used as an id, things go wonky.
string fName = "accord" + i; is interpreted as ordinary HTML when between HTML nodes. Move it up right after the #for or wrap it in #{ //.. }
#for (var i = 0; i < 10; i++) {
var fName = "accord" + i;
<h3>i = #i</h3>
<div id="#{#fName}">
//..
</div>
}
or
#for (int i = 0; i < 4; ++i)
{
//add a nested months accordion for every year
<h3>i = #i</h3>
#{
string fName = "accord" + i;
}
<div id="#fName">
//..
</div>
}
I do have same problem, and I found a solutions,
In my case, not only I want to populate the attributes in my single page, but also want to pass a definite value to my partial view so that I may able to re-use it.
Warning: My codes looks awful, i'm still finding my way out to improve it.
#{ ViewData["suffix"] = "RF"; }
<div #{ViewData["myId"] = "foo" + ViewData["suffix"];}
id=#ViewData["myId"]></div>
Now, before I call a partial view, I update the ViewData["suffix"] in order to ensure that all my replicated partial view has a unique id.
Calling the partialView it would be
<div id="partialView1">#{Html.RenderPartial("_partialView", ViewData);}</div>
I'm leaving this code, just in case someone needed it. cheers!
<div id="#($"text{i}")"></div>
Ok, got it figured out...
The problem was that I was only very convinced that it didn't work, while it actually worked. The result didn't look as expected, but that's not what convinced me that it didn't work. But I always checked the id of the div in the debugger inside visual studio... turns out that visual studio does not show the actual name of the div, but the uninterpreted code with which it was declared. The id when I examined the element in the browser was correct, in the end.
Only that I'm pretty new to this whole web-thing, exclusively working with C++ (non .NET) before now, so I don't yet know where all the things are and how they behave... it's part of the learning process I guess.
Thanks for the answers. They all worked once I knew where to look if they work.
#dawidr: Your line was missing a closing bracket, so that's what produced the error. I noticed it once I took a closer look at it ;)
string strDynamicId= "fuFileUpload_" + #item.FeildID;
<input type="file" accept=".pdf" name=#strDynamicId id=#strDynamicId />
This worked for me
you should try this

Partial View MVC 5 : "A space or line break was encountered after the "#" character [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Here is the error:
"A space or line break was encountered after the "#" character. Only valid identifiers, keywords, comments, "(" and "{" are valid at the start of a code block and they must occur immediately following "#" with no space in between.
I am using MVC 5 and working through the book Pro ASP.NET MVC 5 - Adam Freeman. Here is the List.cshtml.
Main view
#model SS.WebUI.Models.ProductsListViewModel
#{
ViewBag.Title = "Products";
}
#foreach (var p in Model.Products)
{
#Html.Partial("ProductSummary", p)
}
<div class="pager">
#Html.PageLinks((SS.WebUI.Models.PagingInfo)Model.PagingInfo, x => Url.Action("List", new { page = x }))
</div>
Partial view
#model SS.Domain.Entities.Product
<div class="well">
<h3><strong>#Model.Name</strong>
<span class="pull-right label labelprimary"> # Model.Price.ToString("c") </span>
</h3>
<span class="lead"> #Model.Description</span>
</div>
I have tried various syntaxes and cannot get it to work - any help will be apprecaited!
Most probably you check your partial view code:
# Model.Price.ToString("c")
There is space after # for Model.Price.. # Model.Price.ToString("c") --> #Model.Price.ToString("c")

Dynamically added input field in ui:repeat is not processed during form submit

I am trying to make a input form for answers in my application and I start with four "empty" answers which the view loops over and make input fields for. I have an add answer button which I add one question to the array of answers and then the view render the answers again, but now with an additional input field. The backing bean is viewscoped. However if I submit the form without pressing the add answer button it all works. The data is saved in the database. But if I add an answer after the four is filled out the last one does not get the data from the inputfield (answer.description). If I press the add answer first (without filling out any input fields) the data from the fields are not captured at all leaving all 5 empty so no data is saved in the database.
I have this in the form:
<ui:repeat var="answer" value="#{bean.answers}">
<div class="field">
<h:outputLabel for="answerAlternative-#{answer.serialNumber}"
value="Svaralternativ #{answer.serialNumber}" />
<h:inputText id="answerAlternative-#{answer.serialNumber}"
value="#{answer.description}" size="40" />
</div>
</ui:repeat>
This is the method for creating a new input field:
public String addAnswer() {
if (answers.size() + 1 < 6) {
Answer answer = new Answer();
answer.setSerialNumber(answerSerialNumber + "");
answerSerialNumber++;
answers.add(answer);
}
return null;
}
Used for initializing the answers array with four empty input fields:
#PostConstruct
public void initBean() {
answers = new ArrayList<Answer>();
for (int i = 0; i < 4; i++) {
addAnswer();
}
}
This look to match the current problems of <ui:repeat> in Mojarra. It is totally broken in Mojarra.
You have basically 2 options:
Replace Mojarra by MyFaces which has a way more stable implementation of <ui:repeat>.
Use an UIData component instead of <ui:repeat>, e.g. <h:dataTable>, Tomahawk's <t:dataList>, PrimeFaces' <p:dataList>, etc.

Resources