Search code examples
jquerymodel-view-controllerviewdata

How to set placeholder text in ASP.NET MVC TextBox


I have a simple Newsletter signup form on my page with 2 textboxes (Name,Email) and a submit button. Upon successful submission, I want to display a success statement using ViewData["Message"]. Prior to wrapping the form in an if statement I could use default text values and jQuery events on it, but after wrapping it doesn't work. Here's the code;

@if (ViewData["Message"] != null)
{
    <span class="visitWriteup">Thank You for Signing Up for Our Newsletter!</span>
}
else
{

    using (Html.BeginForm("MailingList", "Home", FormMethod.Post, new { @class = "MailingListForm" }))
    {
        <span class="visitWriteup">
            Sign Up for Our Newsletter:
        </span>
        <span class="SignUpText">
            @Html.TextBoxFor(m => m.Name, new { @Value = "Name:" })

        </span>
        <span class="SignUpText">
            @Html.TextBoxFor(m => m.Email, new { @Value = "E-Mail:" })

        </span>
        <span class="errorText">@Html.ValidationMessageFor(m => m.Name)</span>
        <span class="errorText">@Html.ValidationMessageFor(m => m.Email)</span>
        <input type="submit" id="btnSubmit" class="btnSubmit" value="Subscribe" />
    }
}

The form not displays without the "Name:" and "E-Mail:" Values in the textboxes and my jQuery functions aren't working correctly either.

$(function () {
   $('#Name').click(function () {
       if (this.value == 'Name:' || this.value == '') {
        $(this).val('');
       }
    });
   $('#Name').blur(function () {
       if (this.value == '') {
          $(this).val('Name:');
       }
    });
});

any help would be appreciated.


Solution

  • Its seems you are setting placeholder text in the input fields in wrong way. Please do as follows:

    <span class="SignUpText">
        @Html.TextBoxFor(m => m.Name, new { placeholder="Name" })
    </span>
    <span class="SignUpText">
        @Html.TextBoxFor(m => m.Email, new { placeholder="E-mail" })
    </span>
    

    Now you don't need to do anything with jQuery.