I use in my mvc5 project Html.BeginForm() html helper.
I need to create the element and set style = "pedding:12px!important"
I saw many examples in the web but the are all uses class, I dont want to declare class I just need to put style as is.
How can I implement it?
You need this overload.
Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { style = "padding:12px" })
Not sure why you would add !important to the CSS if the rule is defined on the element itself. Doesn't that override any CSS anyway?
The use of !important should be reserved for overriding other "!important" rules from libraries you cannot modify.
Related
I am creating some html elements dynamically with code such as
new ButtonElement()
and its easy to add classes like
..classes.add('dropdown-menu')
I want to add the following html to it
data-toggle="dropdown"
but dart doesn't allow me to do so. If I add a new ElementHtml like
new ElementHtml('<button data-toggle="dropdown"></button>')
it says it's invalid. I need it for my bootjack dropdown selector.
Any ideas on this?
I think you need a NodeValidator that has the data-toggle attribute enabled (see also Dart, why does using innerHtml to set shadow root content work but appendHtml doesn't?)
What you can do without NodeValidator is
new ButtonElement()..dataset['toggle'] = 'dropdown';
I want to create a custom razor tag like <text></text> to decide what to do with the html code inside of it. Is there any way to create razor elements like <text></text> element and add it to the razor engine?
I don't want to create any HtmlHelpers for this.
For Examle:
<WYSYWIG>
Hello There!
</WYSYWIG>
or
<WeatherChart City="NY">
</WeatherChart>
Explanation:
Well the idea is to have server tags to be translated (Parsed) to html codes by the attributes given to them. This kind of codes helps junior developers not to be involved with the complexity of controls.
The closest thing to what you are describing is to create display or editor templates. You can then define a template for a model and use it with #Html.DisplayFor() in the view.
Here is a good blog post to get you started aspnet mvc display and editor templates and a quick overview of the structure below.
Example
Model - WeatherChartModel.cs
public class WeatherChartModel
{
}
Display template - WeatherChart.cshtml
<div class="weather-chart">
// Some other stuff here
</div>
View - Index.cshtml
#model WeatherChartModel
#Html.DisplayForModel() // This will output the template view for the model
In order to create custom element handling in razor, such as <text>, you'd need to implement a custom System.Web.Razor.dll (which is responsible for parsing the document). Specifically, the class you're looking to re-implement would be the System.Web.Razor.Parser.HtmlMarkupParser.
However, I don't believe this is necessary given how flexible the framework itself is. If you're looking to keep things modular, have a look at either using DisplayTemplates/EditorTemplates or consider writing your own extension method. For example, either of the following would be more ideal:
#* TextField is decorated with UIHint("WYSIWYG"), therefore
calling ~/Views/Shared/EditorTemplates/WYSIWYG.cshtml *#
#Html.EditorFor(x => x.TextField)
#* WeatherField is decorated with UIHint("WeatherChart"), therefore
calling ~/Views/Shared/DisplayTemplates/WeatherChart.cshtml *#
#Html.DisplayFor(x => x.WeatherField)
Alternatively:
#* Custom extension method *#
#Html.WysiwygFor(x => x.TextField)
#* Another custom extension method *#
#Html.WeatherChartFor(x => x.WeatherField)
I want to add some custom attributes to the input generated by #Html.EditorFor, I tried the following:
#Html.EditorFor(model => model.Percent, new { #class = "percent" })
But it just ignores my class, from what I can tell from searching around is that the template doesn't support adding custom attributes.
But how does one create a custom template adding support for the custom attributes, while keeping all the functionality of the old template?
Using jQuery this could be done easily
$("input").addClass("class-name")
Input tag
#Html.EditorFor(model=>model.Name)
For DropDownlist u can use following code
$("select").addClass("class-name")
for Dropdownlist
#Html.DropDownlistFor(model=>model.Name)
Please see the following posts, this question has been asked before on Stackoverflow.
Add css class to Html.EditorFor in MVC 2
Set the class attribute to Html.EditorFor in ASP.NET MVC Razor View
ASP.NET MVC 3 Razor - Adding class to EditorFor
There are many more examples, just Google it.
I hope this helps.
The accepted answer is incorrect.
Html.EditorFor ignores custom css class
This behavior is by design.
http://aspnetwebstack.codeplex.com/workitem/223
Try This it works for MVC3
#Html.EditorFor(model => model.Percent)
<style type="text/css">
#Percent
{
width:100%;
}
</style>
In my MVC views I frequently need to reference various elements from JavaScript, and for that purpose I define the id attribute for those elements. This is often in conjunction with Ajax calls that update content of various container elements.
A short example (Razor):
<table id="PersonList">
...
</table>
<div id="PersonDetails">
<!-- This would be loaded dynamically using Ajax -->
<input type="hidden" name="CurrentPersonId" value="#Model.PersonId">
...
</div>
This contains three "magic strings": "PersonList", "PersonDetails" and "CurrentPersonId". An Ajax call might look like this:
$('#PersonDetails').load('#Url.Action("GetPersonDetails")', { PersonId: ... });
Again, the magic string "PersonDetails" appears.
Not good!
Can anyone suggest some "best practice" to define these magics string in a single place and use them in 1) the views, 2) preferably static JavaScript files that implement Ajax calls etc, and 3) CSS files?
I'm, thinking perhaps _Layout.cshtml could include an partial view that defines the magic strings for that controller or even for a specific action. It would examine what controller and/or action called it, and call the appropriate partial view based on that. I do something similar for .css and static .js already, letting me simply add Person.css and have that automatically included for all views for the Person controller.
The partial view would do something like this:
#{
const string PersonListId = "PersonList";
const string PersonDetailsId = "PersonDetails";
const string CurrentPersonIdName = "CurrentPersonId";
}
<script type="text/javascript">
NamesAndIds = {};
NamesAndIds.PersonListId = '#Html.Raw(PersonListId)';
NamesAndIds.PersonDetailsId = '#Html.Raw(PersonDetailsId)';
NamesAndIds.CurrentPersonIdName = '#Html.Raw(CurrentPersonIdName)';
</script>
This should let Razor code use the C# string consts to generate appropriate HTML, and static JavaScript files could reference NamesAndIds in jQuery selectors etc. (Assumes that the consts defined in the partial view will be available in the calling view, which I doubt (haven't checked it yet)... How to use them in .css files I don't know.
Any better suggestions? How do you handle this problem?
I hope someone can come up with something better, but this is at least something.
In the main (non-partial) view I have a section at the top that defines the ids and names I need to use in multiple places in C#, HTML and JavaScript:
#{
const string PersonListId = "PersonList";
const string PersonDetailsId = "PersonDetails";
const string CurrentPersonIdName = "CurrentPersonId";
}
At the bottom, I have a script section that assigns the strings to suitable namespace container objects:
<script type="text/javascript">
MyNamespace = {};
MyNamespace.Ids = {};
MyNamespace.Names = {};
MyNamespace.Ids.PersonList = '#Html.Raw(PersonListId)';
MyNamespace.Ids.PersonDetails = '#Html.Raw(PersonDetailsId)';
MyNamespace.Names.CurrentPersonId = '#Html.Raw(CurrentPersonIdName)';
</script>
In each partial view that introduces additional items that I need to reference by id or name, I add similar code to extend MyNamespace.Ids and MyNamespace.Names with the required strings.
Now I can use the C# string constants in Razor view code to generate markup with the right ids and names and I can write regular static JavaScript files that reference MyNamespace.Ids and MyNamespace.Names to find the right ids and names, e.g. in jQuery selectors.
I also added similar stuff for action URLs that my Ajax calls use, and put them in MyNamespace.Urls:
MyNamespace.Urls.GetPerson = '#Html.Raw(Url.Action("GetPerson"))';
It's not ideal but it's straightforward and solves the most pressing issue of magic strings scattered all over the place. It will not detect errors at compile time, but renaming items will require a single string to be renamed at a single place, and if I rename or misspell MyNamespace.Ids.Something it will at least generate a runtime JavaScript error that can be seen in a JS console or similar.
For actions and file names (js, css) use T4MVC.
T4MVC is a T4 template for ASP.NET MVC apps that creates strongly
typed helpers that eliminate the use of literal strings in many
places.
I wouldn't worry about ids and css class names.
Try defining custom routes
PeopleLists/{PeopleList}/Person/{PersonID}
Then your URL would look like this
http://www.mysite.com/PeopleLists/Friends/Person/Pete
ASP.NET MVC can generate HTML elements using HTML Helpers, for example #Html.ActionLink(), #Html.BeginForm() and so on.
I know I can specify form attributes by creating an anonymous object and pass that object for the (fourth in this case) htmlAttributes parameter where specifying an id for the element:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { id = "MyForm"})
But what about the class attribute? Obviously this does not work:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { class = "myclass"})
As that just throws random syntax errors when my view is requested, because it expects something else after encountering the C# keyword class.
I've also tried:
new { _class = "myclass"}
and
new { class_ = "myclass"}
But they also did not work, as the underscores get replaced by dashes.
I know that I can just as well write the HTML elements by hand or wrap the form inside a <div class="myClass">, but I'd still be interested to know how it is supposed to be done.
In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, #:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new { #class = "myclass"})
For VB.NET this syntax would be accomplished using the dot, ., which in that language is default syntax for all anonymous types:
Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.