1

I'm writing my first ASP.NET MVC application and there is one big problem for me. I want to make a control which will represent a form, but when I try to generate labels and textboxes it returns to me empty page.

So, this is my model file (MyModel.cs):

namespace MyNamespace.Models
{
  public class MyModel
  {
    [Required(ErrorMessage = "You have to fill this field")]
    [DisplayName("Input name")]
    public string Name{ get; set; }
  }
}

This is MyFormControlView.ascx file with my control:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.Models.MyModel>"%>
<div>
    <%
        using (Html.BeginForm())
        {
            Html.LabelFor(m => m.Name);
            Html.TextBoxFor(m => m.Name);
            Html.ValidationMessageFor(m => m.Name);
        }
    %>
</div>

And this is my Index.aspx file where I render the control:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Main.Master" Inherits="System.Web.Mvc.ViewPage<System.Collections.IEnumerable>" %>

<asp:Content runat="server" ID="MainContent" ContentPlaceHolderID="MainContent">
This is my control test!
<%Html.RenderPartial("MyFormControlView", new MyNamespace.Models.MyModel { Name = "MyTestName"}); %>
</asp:Content>

So, when I run my application the result is lonely caption: "This is my control test!" and there are no label or textbox on the generated page. If I inspect the source code of the generated page I can see my <div> block, but it's inner text is empty.

1 Answer 1

6

These methods return strings with the generated HTML code.
You aren't doing anything with their return values.

You need to print the return values on the page using the @ sign:

<%= Html.LabelFor(m => m.Name) %>

Note that since these aren't statements, there shouldn't be a ;. In your example, the ; is harmless (it gets parsed as an empty C# statement); had it been inside of an HTML tag, it would have printed a ; to the HTML source.

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

2 Comments

Your code doesn't work for me, it returns an error "semicolon required". But I guess this is because I'm using ASPxView Engine instead of Razor. And I found the solution depends on your code: <%= Html.LabelFor(m => m.Name) %> - this is works for me. Thank you!
@Ceridan: You're right; I had assumed you were using Razor. Fixed.

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.