adding a class to EditorFor - razor c# - c#

(The editor is for a DateTime property called "ADate"
I am trying this but it does not work.
#Html.EditorFor(model => model.ADate, new { cssClass = "date" } )
So I tried this:
#Html.TextBoxFor(model => model.ADate, new { #class = "date" })
but it outputs type = text.. ofcourse it does.
So I tried a template... I added a folder in shared:
Shared/EditorTemplates
and then I created a .cshtml partial view called Date.cshtml
Now what on earth do I put inside it :O...
I have tried to understand lots of posts and stack overflow entries but it's not sinking in.
The goal is to attach a datepicker to the class ".date" across the entire app where ".date" class is used... The TextBoxFor works with my adding class part... but as I said, the type changes from date to text :(

Ok so this is what you can do:
In your EditorTemplates folder create a template called DateTime.cshml (the name will resolve automatically if you use it for dates, otherwise you have to specify it when using it).
Then in it:
#model System.DateTime
#Html.TextBox(
string.Empty,
Model.ToString("yyyy-MM-dd"),
new { #class="datepicker", #type = "date"})
Using the last parameter you can specify any html attribute (class, data, type etc.).
Then you use it like this:
#Html.EditorFor(x => x.ADate)
In case you chose to name your template with a different name you can specify it by invoking another overload:
#Html.EditorFor(x => x.ADate, "MyOtherAwesomeTemplate")

The EditorFor html helper does not render a date picker for your DateTime attributes (if that's what you want to do). The default EditorFor for DateTime is a text input. If you want to use a date picker, you'll have to use jQuery DatePicker (or any other third party date picker).
Also, the EditorFor helper does not have a parameter for html attributes. If you want to assign a class, you'll have to use TextBoxFor.
In your main View, use the EditorFor like this:
#Html.EditorFor(model => model.ADate)
Then, in your Editor Template (Date.cshtml), you'll have:
#model System.DateTime
<script type="text/javascript">
$(function () {
$(".date").datepicker();
});
</script>
#Html.TextBox("", Model.ToString("d"), new { #class = "date" })
You can download the jQuery UI from here: Download jQuery UI
And, you can learn more about the jQuery DatePicker here: jQuery DatePicker

You can do this
#Html.EditorFor(model => model.ADate)
<style type="text/css">
#ADate
{
#* your css properties goes here *#
}
</style>
this works fine for MVC3 Razor

Related

How to render html code in #Html.TextBox asp .Net MVC?

Hi I'm creating MVC application and I'm using tinyMCE. Sometimes i need to change tinyMCE with simple TextBox field. I'm trying this with hide and show. At the begging I'm showing TextArea and hidding TextBox, but when user click convert tinyMCE to simple textBox field, I'm hidding textArea and showing TextBox.
This is my tinyMCE field
#Html.TextAreaFor(model => model.supTitle, new { htmlAttributes = new { #class = "form-control" } })
and this is simple TextBox
#Html.TextBoxFor(model => model.supTitle, new { htmlAttributes = new { #class = "form-control" } })
but when I'm using TextBoxFor I have something like this
<p> some text</p>
but I want only some text to be displayed without <p> tags.
Also when I save the changes only the changes from TextArea are saves into database.
If the value stored in the model.supTitle property contains Html as a string you would have to parse out the html before rendering the value to a standard input[type=text].
Only the first value is persisted to the database because both form elements have the same name, when the form is posted both values will be sent in the Http Post but the MVC model binding will only map the first form value to the model (which in this case is the text area).
Hiding & showing a html element does not prevent the value of the element from being posted in a form post, you would need to either remove the element from the DOM altogether or change the element name so that it is not bound by the model binder.
Try using this in your view
#Html.Raw(Model.YourTinyMCEContent);

Applying css class using Html.DisplayFor inside razor view

Inside razor view I used model for rendering label like
#Html.LabelFor(model => model.MyName, htmlAttributes: new { #class = "control-label col-md-6" })
and now I want to use it's value instead of data annotation attr. value so I tried with DisplayFor like
#Html.DisplayFor(model => model.MyName, new { #class = "control-label col-md-6" })
this css class control-label col-md-6 is not apply.
Why?
The difference is that #Html.LabelFor helper function renders a <label></label> tag, and the #Html.DisplayFor helper function does not render any html tag, instead it renders plain text. For example the following code:
#Html.DisplayFor(model => model.MyName, new { #class = "control-label col-md-6" })
returns raw text:
Martin
considering that MyName had the value "Martin". And the code:
#Html.LabelFor(model => model.MyName, htmlAttributes: new { #class = "control-label col-md-6" })
will return:
<label class="control-label col-md-6">Martin</label>
Consider the difference.
Use following (if you want to use #Html.DisplayFor):
<span class"control-label col-md-6">#Html.DisplayFor(model => model.MyName)</span>
DisplayFor doesn't work like the other *For helpers. Like EditorFor, it's what's referred to as a "templated helper". In other words, what it renders is controlled by a template that can be modified. Importantly, for both of these methods, if you look up their documentation in MSDN, you'll see that the parameter that would normal correspond to htmlAttributes with the other helpers, instead refers to additionalViewData with these two. This is because, again, their output is controlled by essentially views, which take ViewData.
Additionally, with DisplayFor in particular, the default templates pretty much just output the value, with no HTML. If you pass a string property, for example, the output will be the value of that string and nothing else. Therefore, there's nothing to tie the HTML attributes to, even if you could pass them in.
If you want to do what you're trying to do, you'd have to create custom display templates. This can be done by adding views named after types (e.g. String, Boolean, Byte etc.) or members of the DataType enum (CreditCard, EmailAddress etc.), to Views\Shared\DisplayTemplates. For example, if you created a view at Views\Shared\DisplayTemplates\String.cshtml, then when you called DisplayFor with a property of type string, that view would be utilized to render it. You could then wrap the value that would otherwise be just output directly in some HTML of your choice and utilize ViewData to apply the appropriate HTML attributes. For example:
<span class="#ViewData["class"]">#ViewData.TemplateInfo.FormattedModelValue</span>
.NET Core 2.2 Razor Pages Resize Checkboxes
Late to the game here but needed to make check-boxes huge compared to how Razor Template displays them. Because I wanted user to see if it was checked or not.
I tried above stuff, didn't work. So I used Chrome Developer Tool to look at what the page was rendering and it showed this for the checkbox:
input[type="radio"], input[type="checkbox"] {
box-sizing: border-box;
padding: 0;
}
And I was going to go find it in the CSS file because I could use all check-boxes to be bigger. However, it said it was located here:
reboot.scss:373
Now, I swear it referenced a different scss file when I first opened in developer. But since it looked like Greek to me, a code slob, I just decided to put this (after trying it in style above) at the top of my Razor Page. Notice I just cloned the hidden style above and just added width and height:
<style>
input[type="radio"],
input[type="checkbox"] {
box-sizing: border-box;
width: 40px;
height:40px;
}
</style>
Now, Here is the Razor control I was displaying. It ends up as a checkbox in html at end, but I believe Razor Page is smart enough to know it was a True/False field and showed it as a text box. But. . . not before it applied the sizing I added!! Hope this helps someone.
<td>
#Html.DisplayFor(modelItem => item.Moderated)
</td>

Creating a new object in a view which passes IEnumerable object

I'm having a bit of pain trying to solve how can I create a new object when I'm passing to my view a IEnumerable.I'm having the creation of the new item in a modal jquery-ui window on the same page.
<div class="form-group">
#Html.LabelFor(model => model.Title)
<div class="col-md-10">
#Html.EditorFor( model =>model.Title)
#Html.ValidationMessageFor(model => model.Title, "Please choose a title that is not empty or less than 3 symbols")
</div>
</div>
So this is the code snippet that I'm trying to implement in the main view from where my js gets the information,but since my model is a collection I cannot access the editor options in my razor view.
This is a part of my js file where I get the values of the items inside the input boxes listed above which do NOT work becase I'm operating on a collection.I cannot change the model so I need a shortcut through it.
$.ajax({
url: "/Course/Create/",
type: "POST",
data:{
Title: $("#itemTitle").val(),
CourseDescription: $("#itemDescription").val(),
CourseCategory: $("#itemCategory").val()
},
You should pass a View Model that will contain both the IEnumerable collection + an object that you would like to submit (with Title, Description and Category properties).
In case you cannot change the model that you are passing to the view you should not use Html.EditorFor but simply Html.Editor (the same applies to Html.LabelFor and other Html extensions that you use there).
Of course you then need to pass appropriate name parameter ( e.g. "itemTitle") to these extensions that will comply with the ones used in the JS code.

How do I edit the CSS of the Html.DisplayFor method in MVC 3?

I am using the following code to display text from my view model in my view:
#Html.DisplayFor(m => m.Name)
When I look at the HTML details in IE9 (which I have to use at work) there is no class associated with the name, it just uses the Body CSS styling instead of the display-field class styling. Does anyone know what might be causing this issue or how I might edit the CSS for the text created?
if it is a label, use proper helper for it as Nataka526 suggests
otherwise put it in a span with a class and update css for that class:
your html:
<span class="name">
#Html.DisplayFor(m => m.Name)
</span>
your css:
.name {
//custom css
}
UPDATE
Another option:
Update your Display Templates to handle a specific ViewData key:
in Views > Shared > DisplayTemplate (create this folder if you don't have it already):
add file String.cshtml:
#model string
#{
string myClass = ViewData["class"]
}
#if(string.IsNullOrEmpty(myClass))
{
#:#Model
}
else
{
<span class="#myClass">#Model</span>
}
you may need to add DisplayTemplates for other tipes as well besides string.
In the view you will write something like this:
#Html.DisplayFor(m => m.Name, new { #class= "name" })
This will add spans around it automatically.
UPDATE
Explanation:
There is an overload on Html.DisplayFor which accepts two parameters: expression and object additionalViewData. So the second parameter that I pass is that anonymous object additionalViewData. I create this object with property called class
Inside of the html helper I then check if there is a ViewData with a key class and if there is, I put output inside a span with that class value.
**
updated variable name from class to myClass since "class" is not appropriate variable name.
DisplayFor is used for templating reasons. If you aren't using a template, then you should just use the item like so: #Model.Name If you want to give it a class or id, then you need to wrap it in a span or div.
Your problem is that you're using the wrong method to output data, and expecting it to do something else. There is no built-in way to output raw data with class names.
So your choices are, wrap the raw item in a container that you can apply the css to, or create a template to use for these, then specify the template name in the DisplayFor like so:
#Html.DisplayFor(m => m.Name, "NameTemplate")

ASP.Net MVC Razor - write tempdata in razor and retrieve from control

I have a single page with a Partial control on it called PartialContact
In reusing this control I would like to change the title within the PartialContact control. i.e.
// change to Title1
#Html.EditorFor(model => Model.Contact1, "PartialContact")
// change to Title2
#Html.EditorFor(model => Model.Contact2, "PartialContact")
// change to Title3
#Html.EditorFor(model => Model.Contact3, "PartialContact")
Whats the best way to pass in title text within Razor? TempData?
(I have multiple different controls I need to do this with aswell)
Many thanks
Chris
Use the ViewDataDictionary to pass the value, e.g.
#{
ViewData["Title"] = "Blah";
Html.EditorFor(model => Model.Contact1, "PartialControl", ViewData);
}
Then access it in the partial with #ViewData["Title"]

Categories

Resources