Can we pass Model.item.value as a CSS class in Mvc3? - css

I have one doubt: can we pass Model.item.value to a CSS class in MVC3?
For example:
#foreach (var items in Model)
{
#Html.TextBox(#items.ShortDesc, #items.SfldDefault, new { #class = "#items.ShortDesc"})
}
I want to print my #items.ShortDesc as the CSS class but it's taking it as a string here.. Any idea?

You just have to write it without the quotation marks and # symbol (no need for those, as you're already inside a code block):
#Html.TextBox(items.ShortDesc, items.SfldDefault, new { #class ="abc "+ items.ShortDesc })

Related

Unable to apply a css class to my #Html.DisplayFor inside a WebGrid, inside my asp.net MVC 5 web application

I have the following code inside my asp.net MVC Razor view:-
#{
List<Marketing.Models.SalesData> allLevels = ViewBag.AllLevels;
var gridcolumns = new List<WebGridColumn>();
gridcolumns.Add(new WebGridColumn()
{
ColumnName = "Status",
Header = Html.DisplayNameFor(model => model.Content.FirstOrDefault().Status).ToString(),
CanSort = true,
Format =
(item) =>
{
var banner = item.Value as Marketing.Models.SalesData;
return Html.DisplayFor(modelItem => banner.Status, new { #class = banner.Status });
}
});
now what i am trying to do is to define a css class inside my Html.DisplayFor(modelItem => banner.Status, new { #class = banner.Status }); but this will render the without any css class, as follow:-
<td>succeed</td>
now i though the problem with the way i am defining the class, so i tried this test, to hard code the class name Html.DisplayFor(modelItem => banner.Status, new { #class = "testclass"}); but this did not render the css class.. so can anyone adivce on this please?
now i am using asp.net mvc version 5.2.3.0 which should support defining css classes inside my HTML helpers.
At first take a look to this example. #Html.LabelFor() Helper function renders a <label></label> tag. Suppose if you write #Html.LabelFor(m=>m.Name, new {#class = "form-control"}) it returns <label class = "form-control">David</label>.So we can apply class to label for helper function.
But #Html.DisplayFor() do not render any html tag. If you write #Html.DisplayFor(m=>m.Name) it returns your name only, like: David.
So you have to wrap #Html.DisplayFor() Helper inside a span and apply class to it.
Like: <span class = "form-control">#Html.DisplayFor(m=>m.Name)</span>. Then output will be <span class="form-control">David</span> . That means class applied on name property.
Hope this helps..

How to add a class to a html element through a ViewBag property?

So if I have a view that gets a model that hasn't anything to do with the html element I want to add a certain class to, how do I do this? I presume I have to use the ViewBag, but I can't figure it out.
The view ends up being like this.
#model CRW.WebUI.Models.ItemsListViewModel
#{
ViewBag.Title = "ListP";
}
<h2>Discounts available</h2>
#foreach (var p in Model.Items)
{
Html.RenderPartial("ProductsListing", p);
}
I want to add the class attribute in this view and I don't want to associate anything with the model. I want that to remain intact.
I want to add the class "selected" on an element a that is defined in a Shared view and that I can identify by its innerHtml string.
You can use ViewBag as below.
<h2 class="#(ViewBag.MyClass)">Discounts available</h2>
#Html.ActionLink("Link Text", "method", "controller", null, new { #class = ViewBag.MyClass })
Thanks!
Using ? operator to set conditional HTML class for example to hide or show simple bootstrap alert div, you can use the new HtmlString() function in System.Web:
<div #(ViewBag.MsgToClient == null ? new HtmlString("class=\"hidden\"") : new HtmlString("class=\"alert alert-light\"")) role="alert">
<h4>Validation Error:</h4>
<h5 class="text-danger">#ViewBag.MsgToClient</h5>
</div>

Vary type of input control based on drop down selection?

I'm building an edit screen where a use can edit rows of data. One of the fields is represented by a drop down, and another is an input field named 'value'. Now, depending on the value in the dropdown, I need to have different kinds of input controls for the value input control. Sometimes it should be a text box, others a datetime control (html5 and / or jqUI date picker), and finally a dropdown list containing a fixed set of values ('Yes' / 'No').
So basically sometimes I need to accept any string data, sometimes a date, and sometimes a boolean (but with a select box, not a check box). What's my best option for implementing this? Ideally the value entered would not be lost moving from one kind of input to another, while the user is on this edit page. On post back, I have a single database value to store (its a sql_variant).
Also, I'm using asp.net mvc3 so an ideal solution will work with the normal Html.ValidateFor and Html.ValidationMessageFor methods.
After lot's of time in JSFiddle, I made this solution. And I think it's pretty cool. It wasn't really that hard. and you can adapt it to whatever you need. just click here.
basically I make variables to represent the possible values. then I make a variable to hold the active element.
Whenever the type selector changes, it calls the change() function which uses if() statements to check what was selected, and then it sets the active element accordingly.
And finally, it calls the hide() function which hides the inactive elements.
here is the updated version
RED ALERT: I realized this didn't work in FF (maybe it was just my browser but whatever).
so I fixed it here
The typical way I accomplish something like this is to actually store 3 different fields in the db for each of the different types of values. Then I create something like the following html:
<!-- Input type selector -->
<div class="cell variable-selector">
<select><option ...</select>
</div>
<!-- varied input -->
<div class="cell variable show-text">
<div class="text"><input type="textbox"></div>
<div class="date-picker"><input type="textbox" class="datepicker"></div>
<div class="drop-down-bool"><select><option ...</select>
</div>
Then I have css that hides or shows the correct input element based on which class the cell has:
div.variable div { display:none }
div.show-text div.text { display: inline }
div.show-date-picker div.date-picker {display: inline }
div.show-drop-down-bool div.drop-down-bool {display: inline}
lastly you can setup some javascript so that when you change your variable-selector you change the class of your variable cell. Which jquery one might do this as so:
$(document).ready(function() {
var variableSelector = $("div.variable-selector > select");
variableSelector.change(function() {
var type = $(this).text();
var class = "cell variable show-" + type;
var variableCell = $(this).parent().parent().find("variable");
variableCell.attr("class", class);
})
});
As a quick warning I wrote the above code on the fly in the stack overflow editor window so there might be a couple of syntax errors or a minor bug somewhere but the basic idea should work. Hope it helps.
--Adam
In case you want to make full use of mvc3 validations, consider this approach.
Model
public class MultiValueViewModel
{
[Required]
public string TextValue { get; set; }
[Required]
public bool? BooleanValue { get; set; }
public MultiValueType ValueType { get; set; }
}
public enum MultiValueType
{
Text,
Boolean
}
View
#model MultiValueViewModel
#Html.DropDownListFor(m => m.ValueType, new SelectList(new[]
{
MultiValueType.Text,
MultiValueType.Boolean
}), new { #id = "multi_value_dropdown" })
<p>
<div data-type="#MultiValueType.Text" class="multi-value-pane">
#Html.EditorFor(m => m.TextValue)
</div>
<div style="display: none" data-type="#MultiValueType.Boolean" class="multi-value-pane">
#Html.DropDownListFor(m => m.BooleanValue, new SelectList
(new [] {
new SelectListItem { Text = "Yes", Value = "true"},
new SelectListItem { Text = "No", Value = "false"}
}, "Value", "Text"), optionLabel: "[Not Set]")
</div>
</p>
Javascript:
<script type="text/javascript">
$(function () {
$("#multi_value_dropdown").change(function () {
var value = $(this).val();
$(".multi-value-pane").each(function () {
$(this).css("display", value == $(this).attr("data-type") ? "block" : "none");
});
});
})
Inside your controller, receive MultiValueViewModel value (alone or inside parent model), and based on selected ValueType save to database. Please note that you will need jquery.validate version 1.9 if you need to skip validation on hidden fields (e.g. :hidden).

specify name of dropdownlist asp.net mvc3 razor

I am wondering why the following code:
#Html.DropDownList("Classification.Nationality.NationalityId", Model.Nationalities, new { #size = 10, #style = "display:none;", #class = "pickList" })
produces the following html, specifically why the name of the element is not "Classification.Nationality.NationalityId".
<select style="display: none;" size="10" name="CollectionCategory.Classification.Nationality.NationalityId" id="CollectionCategory_Classification_Nationality_NationalityId" class="pickList">
where the function signature sure looks like this:
public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes);
It seems like the name parameter gots overriden by view model of the parent view. ( This is in a partial view). Does this make sense to anyone?
It's because you are calling this helper inside an editor template or partial for a navigational property called CollectionCategory. It's perfectly normal behavior and ensures that proper value is sent to the controller action when binding. Also I would recommend you using the strongly typed version of this helper to avoid those refactor unfriendly magic strings:
#Html.DropDownListFor(
x => x.Classification.Nationality.NationalityId,
Model.Nationalities,
new {
#size = 10,
#style = "display:none;",
#class = "pickList"
}
)
Of course if you don't want to follow conventions (no idea why wouldn't you) but you could specify a binding prefix in your POST action:
[HttpPost]
public ActionResult Foo([Bind(Prefix = "CollectionCategory")] ClassificationViewModel model)
{
...
}

Styling HTML helpers ASP.NET MVC

If I have an HTML helper like so:
Name:<br />
<%=Html.TextBox("txtName",20) %><br />
How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?
You can pass it into the TextBox call as a parameter.
Name:<br/>
<%= Html.TextBox("txtName", "20", new { #class = "hello" }) %>
This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the # character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.
This is how to add a class and a style on the same element...
"x" being the model passed to the view with a property of TextBoxID
#Html.TextBoxFor(x => x.TextBoxID, new { #class = "SearchBarSelect", style = "width: 20px; background-color: green;" })
I did some research and came across this article that seems to have a solution to your question.
Ajax Control Toolkit with ASP.NET MVC#
source: jimzimmerman
ARTICLE LINK
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330
QUOTE
So basically if you put the class name
TextboxWatermark on any textbox input
with the title you like to show as the
watermark like this:
<input type="text" class"TextboxWatermark" name="username" id="username" title="Must be at least 6 chars" />
or
<%= Html.TextBox("username", new { #class = "TextboxWatermark", #title = "Must be at least 6 chars" }) %>
What is nice about the second option
is that you get the added benefit of
getting the View Engine to fill out
the value of the textbox if there is
an item in ViewData of the
ViewData.Model that has a var named
'username'.
Use the htmlAttributes parameter with an anonymous type, like tihs:
<%=Html.TextBox("txtName","20", new { #class = "test"}) %>
the helper implementation
public static class LabelExtensioncs
{
public static MvcHtmlString Alarm(this HtmlHelper helper, string target, string text)
{
return MvcHtmlString.Create(string.Format("<p class='alert' style='background-color: #b8f89d;border-radius: 5px;width: 100%;'><b>{0}</b><br /><i>{1}</i></p>", target, text));
}
}
the usage in view section
#Html.Alarm("Title", "please unsure your card no is invisible in your authorized information")
the result
Theres no need to use span, because its not dynamic.
Css:
.testClass {
color: #1600d3;
}
View (Index):
#Html.TextBox("expression", "Text to show.", new { #class = "testClass" })
if you need dynamic options you can use for example:
CSS:
.test class{
background: #ffffff;
}
Controller (Index for test):
[HttpGet]
public ActionResult Index()
{
ViewBag.vbColor = "#000000";
return View();
}
View (Index):
<div>
<span>
#Html.TextBox("expression", "Text to show.", new
{ #class = "testClass", #style="color: " +
#ViewBag.vbColor })
</span>
</div>
Hope it helps.
Is it that much more work?

Resources