2

I have a question on how to create custom View Helpers. I would like, in my Index View, to change my default dateTime format. I want to write my own Helper as I thought it was easy like in e.g. PHP. I did:

  1. Created Class:

    public static class CustomViewHelpers
    {
        public static MvcHtmlString returnDateString(string format, DateTime date)
        {
            return MvcHtmlString.Create(date.ToString(format));
        }
    }
    
  2. I added it to the web.config,

  3. I used it like that:

     <p><em>
        Birth date</em>
        <%: CustomViewHelpers.returnDateString("D", Model.Birth_Date); %></p>
    

But I always get the error:

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1026: ) expected

But I think it is a wrong error because when I remove my line it works correctly and I see there are these ")" marks. Can you explain to me why this kind of helper does not work? Maybe you know a good tutorial on how to write your own helpers in ASP.NET MVC2?

1 Answer 1

5

Remove the ; from the call to the helper.

<%: ... %> hold expressions, not statements, and should not have semicolons.

Sign up to request clarification or add additional context in comments.

7 Comments

When I remove this ; I have: Error 2 The best overloaded method match for 'Adventure_v1.Helpers.CustomViewHelpers.returnDateString(string, System.DateTime)' has some invalid arguments But I do not understand why?
Yes I can read (O_o) the error message but first parameter is "D" so it is string and the second it is DateTime in my database so I dont understand why it returns this error. Maybe in view it is changes somehow but for what?
Ok, I do not know why but it does not have DateTime type in view, but I made it work. Thanks for sarcasm rather to explain why it is like this... But thanks anyway. I did: DateTime.Parse(Model.Birth_Date.ToString())
That wasn't sarcasm. The first error message doesn't have any useful information. I suspect that your model type was wrong, but I need other error message.
By the way, it is interesting for me why ; is so important and why when I had it, I did not have this error message. Thanks SLaks once again! <shame> Sorry I missed "other". Sorry once again for misunderstanding
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.