I am working with mvc4 and displaying data from my model in to cshtml views.
When setting data in to the markup, I adding it in to div tags.
Is there a way in mvc that if the model property is not set, dont display the div?
Sample of my markup
<div class="myclass"> #Model.Text </div>
You can test for a value being set like so:
#if (!string.IsNullOrEmpty(Model.Text))
{
<div class="myclass"> #Model.Text </div>
}
Update: If you want to incorporate the logic for whether or not to render an element based on its value, you could create a Custom HTML Helper method.
How about wrapping it in a null check
#{
if (#Model.Text != null)
{
<div class="myclass"> #Model.Text </div>
}
}
Related
I am using
<div class="row">
<div class="col-lg-12 breadcrumb" >
#Html.MvcSiteMap().SiteMapPath("")
</div>
</div>
to display the sitemap of current page. How do i check if the Sitemap exists for the Current page and then only display it?
like:
#if([Check Exists]){
<div class="row">
<div class="col-lg-12 breadcrumb" >
#Html.MvcSiteMap().SiteMapPath("")
</div>
</div>
}
By default, the SiteMapPath HTML helper already does this check. If there is no node that corresponds to the current request the SiteMap.CurrentNode property will be null. When that happens, no HTML will be output from the SiteMapPath HTML helper.
If that isn't good enough to cover your particular use case, you can use the built-in FilteredSiteMapNodeVisibilityProvider, a custom visibility provider, or security trimming to hide the nodes you don't want visible.
Failing that, you could create a custom partial view template for the SiteMapPath or create a custom HTML helper based on the SiteMapPath if nothing else meets your needs.
How does one conditionally render an HTML element in Razor 2?
For instance, suppose I had the tag
<div class="someclass">
<p>#somevalue</p>
</div>
And I wanted to suppress the <-div-> tag from rendering if the value of #somevalue was equal to 1. Is there a simple way to do this in Razor similar to how I might "hide" the <-div-> tag with Knockout.js in a browser, where I might :
<div class="someclass" data-bind="showWhenTrue: someValue != 1">
<p data-bind="text: someValue"></p>
</div>
At the moment, the best Razor alternative I have is to do this:
#if (someValue != 1) {
<div class="someclass">
<p>#somevalue</p>
</div>
}
There are many ways to do this. First, it should be noted that your knockout code doesn't actually remove the html from output, it just sets its display to hidden.
The razor code you have actually removes the code from the rendered HTML, so that's a very different thing.
To answer your question, we need to know what it is you're trying to achieve. If you just want to hide the display, you can simply do something like this:
<div class="someclass" style="display: #{ somevalue == 1 ? #:"none" : #:"block" };">
<p>#somevalue</p>
</div>
You could also do it with a class:
<div class="someclass #{ somevalue == 1 ? #:"HideMe" : #:"ShowMe" }">
<p>#somevalue</p>
</div>
If you want to remove the code from the output, then you can just do what you've done.. i'm mot sure what you find so objectionable about it... but if you want other alternatives, you could create an Html helper, you could use a razor helper, you could use a Display or EditorTemplate....
The list is actually quite long and i'm just scratching the surface...
An elegant (and re-usable) solution is to write an extension method for Html to do conditional rendering of text ( a bit like IF() in Excel) - e.g.
public static MvcHtmlString ConditionalRender(this HtmlHelper helper, bool condition, string trueString, string falseString = "")
{
return MvcHtmlString.Create((condition) ? trueString : falseString);
}
You can then use it in your code as such:
<div class="someclass" style="display: #Html.ConditionalRender(somevalue == 1, "none","block")">
<p>#somevalue</p>
</div>
I am having multiple forms in one page and that page inherits one single model.Every form submission requires a common value. So, common value is stored in hidden field. The hidden field is kept global i.e outside of all the forms but my problem is whenever I submit form, that hidden field is coming to be empty.The hidden field is #Html.HiddenfieldFor(m=>m.FkId) and this FkId is of string type proprty in model i.e public string FkId{get;set;} .Can somebody please guide me how to handle this situation. If I keep hidden field in one of the forms then , it is coming in controller but only for that form submission where I have kept it. But I want that property to be set once and can use in all the form submissions.Please help me. How can I sort out this problem
Some related code
<div id="tabs">
<ul>
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
</ul>
<div id="tabs-1">
#using (Ajax.BeginForm("Evaluation","SaveTab1"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab1" value="Submit" onclick="CheckUser();"/>
}
</div>
<div id="tabs-2">
#using (Ajax.BeginForm("Evaluation","SaveTab2"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab2" value="Submit" />
}
</div>
<div id="tabs-3">
#using (Ajax.BeginForm("Evaluation","SaveTab3"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab3" value="Submit" />
}
</div>
</div>
<script type="text/javascript">
function DisplayMessage(Json)
{
alert( $("#fkID").val(Json.hdn));
// and Alert is showing the value
$("#fkID").val(Json.hdn);
}
</script>
In the Controller I have:
public ActionResult SaveTab1(Model obj)
{
tbl ob =new tbl();
ob.FkId=Obj.fkID;
// after saving, I return
return json(new{hdn=Obj.fkID})
}
public ActionResult SaveTab2(Model obj)
{
tbl ob =new tbl();
ob.FkId=Obj.fkID;
//after saving, I return
return json(new{hdn=Obj.fkID})
}
Similar for tab three, but unfortunately the hidden filed only comes for first form submit. Then I return value to view by json and again set the hidden field property but then it comes null for second form.Please help
First of all, your View does not inherit the Model, it is strongly-typed to the type of your Model. These two are completely different.
But, to answer your question, there's no such a thing as a global hidden field. Fields are not variables. If you want a field to be posted to your Controller, you need to put it inside the form. If you have multiple forms in your View, then you'll have to put the same hidden field inside all the those forms. So, you need to put #Html.HiddenFor(m => m.FkId) inside all the forms in your View.
UPDATE: By the way, it's not Html.HiddenFieldFor, it's Html.HiddenFor.
I have solved the problem. Instead of taking same field in all the forms which was not working, I have taken a unique and different Hidden field properties and after on seperated success function of each form and set the every hidden field a value in success method.
UPDATE:
More general question what is the way to make a higher-order composition of views? The same way you pass a delegate into a method.
ORIGINAL QUESTION:
I have a page view and a control as a partial view. From the page view I render the control using Html.Partal("MyControl", myControlModel). Now this control has some areas that I wish were customizable from the page view. So that if the control is rendered from a different page these areas are filled with different content. Basically what I am looking for is a way to inject a piece of HTML from the page view into a partial view. Can I do it in MVC? If so, how?
Example:
Page view:
<div class="page">
#Html.Partial("MyControl", myControlModel, #<text>My <b>custom</b> piece of HTML which is different for each page<text>)
</div>
My control view:
<div class="my-control">
<div class="common-part-for-all-pages">
#Model.Value
</div>
<div class="part-that-has-to-be-customized">
#* there must be a piece of HTML provided somehow from the page view *#
</div>
</div>
Expected result:
<div class="page>
<div class="my-control">
<div class="common-part-for-all-pages">
#Model.Value
</div>
<div class="part-that-has-to-be-customized">
My <b>custom</b> piece of HTML which is different for each page
</div>
</div>
</div>
Add new properties to the viewmodel of the partial: "TemplateName" and "TemplateModel". Then do
<div class="my-control">
<div class="common-part-for-all-pages">
#Model.Value
</div>
<div class="part that has to be customized">
#Html.Partial(Model.TemplateName, Model.TemplateModel)
</div>
</div>
Or you could just add a string property "Template" and do
<div class="my-control">
<div class="common-part-for-all-pages">
#Model.Value
</div>
<div class="part that has to be customized">
#Html.Raw(Model.Template)
</div>
</div>
Call it like this
#{
// just set the property
myControlModel.Template = "some html";
myControlModel.Template = Html.TextBox(/*...*/).ToString();
myControlModel.Template = Template("hello").ToString();
}
#Html.Partial("MyControl", myControlModel)
#helper Template(string text)
{
<span>#text</span>
}
ToString() isn't necessary if MvcHtmlString type is used.
You'd need to create controller actions for this, but you can use #Html.Action("MyAction", "MyController", myModelObject) and pass any parameters from the page to partial view in the myModelObject parameter. It can be a bit of overkill but if your control/partial view needs to do any special C# code then this way works pretty well.
Make a class PartialModel, give it two properties string Name and object Model, then use #Html.Partial(pm.Name, pm.Model) in your partial view.
If you want to put different HTML inside every time, the above won't work, so read on.
You can use something similar to Html.BeginForm:
#using (Html.BeginMyContainer())
{
<h3>Hi!</h3>
<p>This is some custom content.</p>
}
(This would be a BeginMyContainer extension method on the HtmlHelper class.)
Your Html.BeginMyContainer method should return a class inheriting from MvcForm, which is IDisposable. In the BeginMyContainer method you'll write whatever HTML comes before the custom content of your container, and in the Dispose method of the returned MvcForm you'll write whatever HTML comes after your custom content.
When Razor processes the code I have above, it will:
Run the BeginMyContainer method at the start of the using statement, writing whatever HTML comes before the custom content
Write the HTML custom content inside of the using statement
Call Dispose on the MvcForm at the end of the using statement, writing whatever HTML comes before the custom content
Related: rolling my own #Html.BeginfBrm()
Inside of an asp.net mvc partial view, I have an Ajax form that posts a value and replaces the contents of its parent container with another instance of the form.
Index.aspx view:
<div id="tags">
<% Html.RenderPartial("Tags", Model); %>
</div>
Tags.ascx partial view:
<% using(Ajax.BeginForm("tag", new AjaxOptions { UpdateTargetId = "tags" }))
{ %>
Add tag: <%= Html.TextBox("tagName")%>
<input type="submit" value="Add" />
<% } %>
The controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Tag(string tagName) {
// do stuff
return PartialView("Tags", ...);
}
The problem is when the new instance of the form returns, the posted value is already stored in the input field. As in, whatever I posted as the 'tagName' will stay in the textbox. Firebug shows that the value is hardcoded in the response.
Is there any way to clear the input textbox's value when returning the partial view?
I've tried:
<%= Html.TextBox("tagName", string.Empty)%>
and
<%= Html.TextBox("tagName", string.Empty, new { value = "" })%>`
neither of which do anything.
EDIT:
I realize there are js solutions, which I may end up having to use, but I was wondering if there were any ways of doing it in the backend?
I'm not sure if this solution is "good enough" for you, but couldn't you just empty the form in a JS callback function from your ajax call? If you're using jQuery on your site, the callback function could look something like this:
function emptyFormOnReturn() {
$(':input').val();
}
I am not entirely sure if it will, but in case the above code also removes the text on your submit button, change the selector to ':input[type!=submit]'.
yes you should use jquery to set values on response
if you change your code to use jquery for ajax operations, you can call you settingvalues function on success callback...example:
http://docs.jquery.com/Ajax/jQuery.ajax#options