[Display(Prompt MVC3 - asp.net-mvc-3

I am trying to setup my model so I can use the
#Html.EditorFor(e => e.publicationTitle) and have it show a Watermark with a hint.
Currently I am doing
#Html.LabelFor(e => e.PublicationTitle) #Html.TextBox("PublicationTitle",tempTitle.ToString(), new { style = "width:350px", placeholder = "Put title here" })
#Html.ValidationMessageFor(e => e.PublicationTitle)
I have found that you can put a [Display(Prompt="Enter title here")] in my model
but it is not showing up in my view for some reason.
On a side note. I did try to follow the instructions from this post
Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?
At the end of this post it says to change the ~/Views/Shared/EditorTemplates/String.cshtml file but this file is not located in my project.
Any hints would be appreciated. Thank you in advance.
FOLLOW UP!
Ah the joys of MVC3. Apparently the above post answers the question once you understand what is going on. If you create the EditorTemplates/String.cshtml file in your ~/Views/Shared/ folder then it will use this template for your editfor boxes.
Final Answer to be concise for others looking will be posted below.

In your controller you need to do the following
[Display(Prompt="First Name Goes Here",Name="First Name")]
[StringLength(100,ErrorMessage="First Name may not be longer than 100 characters")]
public string AuthFirstName { get; set; }
The Prompt="This is what will display" under display is the watermark that will be created.
Then you will need to create the folder "EditorTemplates" under ~/Views/Shared the entire path will be ~/Views/Shared/EditorTemplates/
Then create the file String.cshtml and place the following code in it
#Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue, new { #class="text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })
More detailed information can be found at the link posted by tugberk (SO question and SO answer).

This will not work with IE unfortunately. At least IE9 and earlier. I spent couple hours pulling my hair as to why this helped others and doesn't work here. Apparently IE won't show prompts. Hope IE10 will address the issue.

The placeholder attribute is not supported in earlier versions of IE, so for the Display[(Promt="...")] to work fine I recommend to use (along with the String template as Samack described) any jQuery watermark plugin (I used the google one) then add this to the Document.Ready function:
$(document).ready(function(){
$(':text').watermark({ textAttr: 'placeholder' });
})

Related

Use of older Telerik RTF/HTML editor

My company has a license for one of the older Telerik packages. They would like me to place an RTF textbox in place of the normal Textbox on one of our screens. I have the extant code for the text box and I have another page used in our application which ostensibly works with the RTF editor (it's a part of functionality which is inaccessible to me at my privilege level). The original code was as follows:
#Html.TextAreaFor(m => m.LogEntry.Description,
new { #id = "logDescription", #class = "dirtyField",
style = "width: 400px; height: 100px;" })
The RTF code I'm patterning my code off of is as follows:
#(Html.Telerik().EditorFor(m => m.MessageContent)
.Name("msgEditor")
.HtmlAttributes(new { style = "width: 600px; height:250px; padding-top:0px; padding-bottom:0px;" })
.Tools(tools => tools
.Clear()
.Bold().Italic().Underline().Strikethrough()
.JustifyLeft().JustifyCenter().JustifyRight().JustifyFull()
.InsertUnorderedList().InsertOrderedList()
.Outdent().Indent()
.CreateLink().Unlink()
.Subscript()
.Superscript()
.FontName()
.FontSize()
.FontColor().BackColor()
)
)
I have the Editor control displaying, using our LogEntry.Description string instead of the above MessageContent. I can input text into it. I can load text into it. But when I try to save the entry off of a procedure called by a button in the dialog, the text of Description has been set to NULL. What am I doing wrong? I'm a newbie when it comes to web development, so I'm sort of grasping at straws.
I've looked at the answer at Telerik Editor doesn't work, but we have a ScriptRegistrar set up. The tutorials I can find on the Telerik site are all for the Kendo editor. This page seems more applicable, but, as far as I can tell, I'm doing all of the same things as they are. I tried to figure out if there was a place I needed to insert a call to HTMLEncode or HTMLDecode, but I've yet to find where the value is getting changed to NULL so as to catch it before then. Unfortunately, company code and all of that, I can only post so much of it, although I'll do my best to post sanitized specifics as necessary.
For the sake of future people who have this issue, I hashed it out with one of the programmers here who had access to some additional code that had been published, but not added to our source code. I had to add code similar to the following inside the code run for the Javascript code associated with the Save button:
var editor = $("#descriptionEditor").data("tEditor");
var message = editor.value();
$("#logentry-encoded-message-content").val(message);
Within the CSHTML file, had to add the following element:
#Html.HiddenFor(m => m.LogEntry.EncodedDescription, new { #id = "logentry-encoded-message-content" })
Then, in the code involving processing the form, I assigned the contents of EncodedDescription to Description. Rather annoyingly, I have yet to find a way to just use one variable here. I did also have to add a modifier of [AllowHtml] to the EncodedDescription property to avoid the error message that there is potentially dangerous HTML being posted (since I know exactly what is being posted, and I know that it will be decoded and encoded for the control).

Vote for comments in posts function with Codeigniter and routing

I am trying to create posts with comments with CodeIgniter and I am trying to add voting for the comments with + and -.
But my problem is not actually this functionallity but more exactly creating the link and the method in controller/model for this.
I understand that there is some kind of link to methods.
If I have something like this:
public function like() {
echo 'Test Function';
}
and when I create link like this one sitename.com/posts/first-post/like theoritecally I will see blank page with "Test Function" text (and of course if I write proper routing rule but I cannor for now).
I can see a blank page with this working echo 'Test Function', but does this mean I have to load every methods and views for the entire page if I want to display the entire webpage with all the elements? I think that I mistake something very serious here but I don't know what.
The example with the "Create news" tutorial in ellislab.com didnt help me. They show something similar I think with /create/ section in the URL and create() methods.
If I have many links with functionallities do I have to add new routing rules for all of them? I really tried to search in Google and everywhere but I didnt find anything related.
Sorry for this lame question.
You need to use Ajax call and on callback you have to increase or decrease the count. For creating a link , once page is loading render the data and provided the default link like
for + http://<site.com>/<controller>/like?totalLike=<36>
for - http://<site.com>/<controller>/unlike?totalunLike=<3>
Once user will click + link then by using Ajax, call the controller method link/unlike and increase or decrease the count and repopulate the link again with fresh counter.
Hope it will resolve your problem.

jqGrid: Create a custom edit form

I am wanting to customise the edit form in jqGrid so that instead of using the table structured layout provided I would like to use my own custom css structured layout for the form elements. How should I go about modifying the edit form to allow me to use my own custom look?
You can definitely achieve this by jquery ui dialog. However I can not put full code for you but helps you in the steps you have to do.
1 design your custom form whatever CSS and style you want to apply.
Suppose this is youe custome form
<div id="dialog-div">
<input type="text">
</div>
2 on jquery dialog open the dialog on your jqgrid editbutton click
$("#edit").click(function(){
var rowdata = $("#coolGrid").jqGrid('getGridParam','selrow');
if(rowdata){
$("#dialog-div").dialog('open');
var data = $("#coolGrid").jqGrid('getRowData',rowdata);
alert(data);
}
});
by default it will close as-
$("#dialog-div").dialog({
autoOpen: false,
});
Now as you get data in variable you can put in your edit form and of jquery dialog button save it according to your logic.
Hope this helps you.
I would recommend you first of all to read (or at least look thorough) the code of form editing module which implement the part which you want to replace. You will see that it consist from more as 2000 lines of code. If you write "I would like to ..." you should understand the amount of work for implementing what you ask. If you are able to understand the code and if you are able to write your modification of the code even using libraries like jQuery UI then you can decide whether it's worth to invest your time to do the work. The main advantage of using existing solutions is saving of the time. What you get in the way is not perfect, but using existing products you could create your own solutions quickly and with acceptable quality. The way to study existing products which you can use for free seems me more effective as large investments in reinventing the wheel.
http://guriddo.net/?kbe_knowledgebase=using-templates-in-form-editing
Using templates in form editing
As of version 4.8 we support templates in the form editing. This allow to customize the edit form in a way the developer want. To use a template it is needed to set the parameter template in the edit add/or add options of navigator. This can be done in navigator or in the editing method editGridRow :
$("#grid").jqGrid("navGrid",
{add:true, edit:true,...},
{template: "template string for edit",...}
{template: "template string for add",...},
...
);
and in editGridRow method:
$("#grid").jqGrid("editGridRow",
rowid,
{template: "template string",...}
);
To place the CustomerID field in the template the following code string should be inserted in the template string
{CustomerID}
With other words this is the name from colModel put in { }
The usual problem with table layouts is when you have columns with different widths, especially with those very wide.
I solved my problem adding the attr colspan to wide columns in the beforeShowForm event.
for example
"beforeShowForm":function() {
$('#tr_fieldnameasinColModel > td.DataTD').attr('colspan',5);
}
It's not fancy but it worked for me. Perhaps there is a more elegant way to do the same.
I could arrange the fields in several columns without having to make the form extrawide.
When user click on edit button the page navigate to another page, based on Id get the details of a row and you can display the values..
Previous answer of Creating a link in JQGrid solves your problem.

How do you format localized strings to have single words of a sentence be a link?

I am working on a globalized web-app in ASP.NET MVC3. The project contains the I18N resources files and I normally access the resources inside my Razor views like...
#I18N.MyResourceString
I have a tricky situation which I have not been able to figure out a elegant solution to yet. I need to be able to localized the sentence "Click here to donate." where the word 'here' should be a link to our donation system.
Most links in the site are internal so to create link I simply write...
#Html.ActionLink("Some link text", "MyAction", "MyController")
This donation link is external. What I have so far (which is not working) is...
#String.Format(I18N.ClickHereToDonate, "" + I18N.Here + "")
where the I18N.ClickHereToDonate resource's text is "Click {0} to donate.".
What I see on the screen is...
Click here to donate.
Furthermore, I would also like to add a 'title' attribute to the 'a' tag. It gets even uglier when I try that...
#String.Format(I18N.ClickHereToDonate, "" + I18N.Here + "")
There has to be a better way to form complex strings with embedded tags without concatenating things together in such a hackish manner. Not only does it not work (the intended markup got encoded) but it makes the HTML inside a string literal in my razor template which makes me loose any awesome IDE support/intergation/refactoring capabilities.
How can markup be injected into localized strings?
UPDATE
Adam Tuliper mentioned the #Html.Raw helper method in his answer so I added it to my already ugly markup...
#Html.Raw(String.Format(I18N.ClickHereToDonate, "" + I18N.Here + ""))
This at least got me a click-able link in the outputted markup.
Click here to donate.
It is still a far-less-than-elegant solution though so I am still looking for better ways of doing this.
Maybe try
#I18N.ClickHereToDonate
Overall, you don't need the String format - you can just inject the Razor things inside normal html elements.
Edit: Incorporating the below:
#Html.Raw(String.Format(#I18N.ClickHereToDonate,String.Format("<a href='http://paypal.com' title='{0}'>{1}</a>", I18N.PayPal,I18N.Here)))
Your choices are limited without built in support for this scenario (and there isn't in the helpers)
The cleaner way is to form your urls in a viewmodel and pass that view model to the view so you have minimal html. Your ViewModel contains
public class WhateverIndexViewModel
{
public string Key {get;set;}
public string URI {get;set;}
public string Title {get;set;}
}
Set the info in your controller, pass it to your view and use
#Links["YourKey"].Title"
As a basic idea.
Note if you dont want to use Html.Raw here then your URI in the class would be of type MvcString not String this way #Links["YourKey"].URI won't be html encoded.

MailTo link in Razor

How do I make a mailto link using Razor?
I've seen Html.MailTo, but when I try #Html.MailTo nothing comes up.
Thanks!
You should just make a normal hyperlink:
...
Razor and MVC helper methods are not intended to replace HTML tags; they're intended to make common data-bound elements simpler.
HTML.MailTo() helper is a part of the 'mvc3 futures' project, but there is an alternative to way to do it.
1.)Create a new .cshtml file inside App_Code directory and name it as you want (for example HTMLHelpers.cshtml)
2.)Write the following in the file
#helper EmailTextBox(string email, string title) {
#title
}
3.)Now in your view you can call your new function. For example write
Email: #HTMLHelpers.EmailTextBox("george#example.com","George Chatzimanolis")
I get to this question when I was trying to do simple
Email
but Razor will treat this as text
I know there are HtmlHelpers and such but so far simple code worked for me
Email
Whether a variable comes from model or ViewBag it's about # sign in href and Razor
The mailto helper is a part of the 'mvc3 futures' project.
The below blog will give you more information on mvc3 futures as well as the link to get it. I believe that it is also available as a NuGet package.
http://weblogs.asp.net/imranbaloch/archive/2011/07/26/using-the-features-of-asp-net-mvc-3-futures.aspx
#{var email= new HtmlString( "" mail me ""));}
#email;

Resources