On my main page, I have the code #{Html.RenderPartial("_Partial1.cshtml");}, and on my Partial, I have an HTML string:
#{
// The string is actually dynamic, not static. This is here for simplicity
string abc="<div class=\"error\">abc</div>";
}
#abc
I want to output abc with some CSS error styles, but I actually got <div class="error">abc</div> - of course, no styles there. How do I make it interpreted as HTML source code and not a string?
You can use the Html.Raw() method for that.
And if you are using model in your view than use:
#model YourApp.Models.YourModel
....
#Html.Raw(#Model.NameOfYourProperty)
Related
I have very werid situation. I have a controller with two methods:
#RequestMapping("/gameDetails")
public String gameDetails1(Model model){
model.addAttribute("game",gameService.findById(1L));
return "gameDetails";
}
#RequestMapping("/gameDetails/{id}")
public String gameDetails2(#PathVariable("id") Long id, Model model){
model.addAttribute("game",gameService.findById(1L));
return "gameDetails";
}
When I open /gameDetails URL page is OK,
but when I use /gameDetails/1 whole page is messy, like there's no CSS at all. Im using html pages with Thymeleaf. I tried with style tags inside html and with external CSS loaded with:
<link rel="stylesheet" href="../static/css/gameDetails.css" th:href="#{/css/gameDetails.css}" />
No success. Do you have any idea what is wrong? How is this even possible?
I work on mvc 5 project.
On my _Layout.cshtml I have html element named id="topBar" this element displayed in each page.
But I have page named About.cshtml I don't want this page to display only element id="topBar" all other html elements in _Layout.cshtml I want them to be displayed normal in About.cshtml.
Any idea how can achieve described appearance above?
One simple way of achieving this (without javascript), is to set a value in ViewBag inside your about Action and use it in layout like this:
_Layout.cshtml
#if (ViewBag.ShowTopBar ?? false)
{
<div id="topBar">
</div>
}
Action inside your Controller:
public class MyAwesomeController : Controller
{
public ActionResult About()
{
ViewBag.ShowTopBar = true;
return View();
}
}
There are two options:
1. Add an ID to every body element
You could add an ID to the body of each of your pages that contains for example the Controller and Action name and then add a CSS rule to hide the topBar element on the about page.
First, let's create two string variables for the controller and action name. Do this in your _Layout.cshtml:
#{
string controller = ViewContext.RouteData.Values["controller"].ToString();
string action = ViewContext.RouteData.Values["action"].ToString();
}
Next, add the ID to the body:
<body id="#controller-#action">
In your css, you can now add a rule to hide the topbar in the about page (assuming the controller is called HomeController):
#Home-About #topBar {display:none;}
You could also use an extension method to get the controller and action name. For example something like this.
2. Use jQuery on the About page
You could add a Javascript on your about page and use jQuery to hide the topbar (I assume jQuery is already loaded):
<script>
$("#topBar").hide();
</script>
Easier way, just did that: style your page individually:
<style>
#showcase { display: none; }
</style>
Put this on the page that you want to hide, showcase is my section id. ;)
I want to insert a partial view from NewsController into HomeController.
In my NewsController
public ActionResult LastNewsPatial()
{
var lstLastNews = db.Articles.Take(5).OrderByDescending(m => m.CreatedDate).ToList();
return PartialView(lstLastNews);
}
In Views/News folder i create LastNewsPatial.cshtml
#model IEnumerable<mytest.com.Models.Article>
#foreach (var item in Model) {
<div class="glidecontent">
<img src="#item.ImageURL" style="float: left; margin-right:21px;" />
<strong>#item.Title</strong><br /><br />
#item.Content
</div>
}
In Views/Home/Index.cshtml i insert a LastNewsPatial view
#Html.Partial("~/Views/News/LastNewsPatial.cshtml")
When i run my project then I received a error
Object reference not set to an instance of an object.
at row
#foreach (var item in Model)
in LastNewsPatial.cshtml
How can I fix it?
The reason for your error is that the Model isn't passed to the view... infact the action isn't even called at all. Set a breakpoint and you'll confirm this.
I think you should be calling #Html.RenderAction inside the index instead of #Html.Partial.
Instead of #Html.Partial("~/Views/News/LastNewsPatial.cshtml")
use
#Html.RenderAction("LastNewsPatial","News")
or #Html.Action("LastNewsPatial","News")
You don't need to give .cshtml in name of view when rendering a view. Only give name of PartialView without .cshtml like this.
#Html.Partial("~/Views/Shared/LastNewsPatial")
You can also use #Html.Action() to render your view like this
#Html.Action("LastNewsPatial","News")
This worked for me: #Html.Partial("../Views/Shared/LastNewsPatial")
The .. instead of the ~
Some of the answers here are missing the question
You use this
#Html.Partial("~/Views/News/LastNewsPatial.cshtml")
Which creates a partial view without a model. So in order for this to work you need to pass model.
#Html.Partial("~/Views/News/LastNewsPatial.cshtml", your_model)
Your problem is not view related and you simply pass no object to the partial. How to do it is up to you. Do you want a Html.Partial or Html.Action? Depending on your needs.
P.S.
Use RenderPartial and RederAction they are better practices since Partial and Action return an HTML string where instead using render allows ASP.NET to write directly to the response stream.
I am working on an ASP.NET MVC Project. In my controller I check if ModelState is valid and according to the result I assign a value to IsSucceed:
if (ModelState.IsValid)
{
ModelTutucu.modelim.IsSucceed = true;
}
return View("YaziEkle",ModelTutucu.modelim);
In my view I have a div with a "success" class. I have some text written by Response.Write() to the value of IsSucceed:
<div class="success">
#if(Model.IsSucceed) {
string success = "It is successfully saved.";
Response.Write(success);
}
</div>
The problem is that success doesn't appear in the the div. It appears at top of the page. When I do something like this:
<div class="success">Foo</div>
"Foo" appears in the div, but I cant get the same result with Response.Write, it shows strange behaviour. What is the reason of this problem? How can I solve it? Thanks in advance.
You should use the # instead of Response.Write(). Response.Write() is writing before the razor is rendered and written, so that's why it comes out on top, rather than in the middle or where it should be. Using # makes sure that the string is rendered where it should be according to the html markup.
Like:
#if (Model.IsSucceed)
{
string success = "It is successfully saved.";
#success
}
I need to know whether there is ValidationMessage or not. Because I want to add to " tag into the error message.
like
#if (Html.ValidationMessageFor(m => m.UserId)){
Html.ValidationMessageFor(m => m.UserId) + "<br />
}
the above code does not work, anybody know how it make work?
Thank you!
You need to check the ModelState for that particular error. For example:
#if (ModelState["UserId"].Errors.Count > 0) {
Html.ValidationMessageFor(m => m.UserId) #:<br/>
}
This could get really ugly if you have it everywhere though. If you need to do this a lot, then create a custom Html Helper extension.
if you need to add some markup at your validation message I would suggest you to create a custom one.
All you need to to is create a new helper and encapsulate that logic in the helper itself
somethig like the below
public MvcHtmlString MyValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
//your logic here
}
Your question is very unclear. Please clarify what you want to achieve.
If you would like to show an error if there is one and do not show an error if there is not, you do not need to write separate "if()" logic like Mystere Man suggests.
Just having Html.ValidationMessageFor(m => m.UserId) in a properly formatted by css html and having all proper references to scripts required for validation will do the trick.
By properly formatted html I mean having validation blocks next to the inputs in the div tags so that you do not have to have <br>s for the new lines.