BKahuna
BKahuna

Reputation: 611

Unobtrusive javascript adding data to @Html.HiddenFor

I have a hidden field on a form that is created in Razor using the @Html.HiddenFor helper:

@Html.HiddenFor(model => model.BidID, new { id="bidItemID" })

My View model looks like this:

public class BidEditVM
{
    [Display(Name = "Bid ID")]
    public int BidID { get; set; }

    [StringLength(51)]
    [Display(Name = "Customer Name")]
    public string CustomerName { get; set; }

    [StringLength(75)]
    [Display(Name = "Bid Name")]
    public string BidName { get; set; }

    [Display(Name = "Amount")]
    public decimal Amount { get; set; }

    [Display(Name = "Time")]
    public DateTime BidTime { get; set; }
}

When the HTML is rendered, unobtrusive javascript adds it's stuff to the hidden input field even though it will never require validation:

<input id="bidItemID" type="hidden" value="5198" name="BidID" data-val-required="The Bid ID field is required." data-val-number="The field Bid ID must be a number." data-val="true">

What's odder is that the message and validation it adds aren't even part of the view model for this partial view. The view looks like this:

@model AuctionAdmin.Models.ViewModels.BidEditVM

@using (Ajax.BeginForm("UpdateBid", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "modalBidInfo" }))
{
    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.BidID, new { id="bidItemID" })

    <fieldset>
        <legend>Edit Bid</legend>

        <div class="display-label">@Html.LabelFor(model => model.CustomerName)</div>
        <div class="display-field">
            @Html.DisplayFor(model => model.CustomerName)
        </div>

        <div class="display-label">@Html.LabelFor(model => model.BidName)</div>
        <div class="display-field">
            @Html.DisplayFor(model => model.BidName)
        </div>

        <div class="editor-label">@Html.LabelFor(model => model.Amount)</div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Amount)
        </div>

        <div class="editor-label">@Html.LabelFor(model => model.BidTime)</div>
        <div class="editor-field">
            @Html.EditorFor(model => model.BidTime)
        </div>
    </fieldset>
}

Where is it getting this metadata from and how can I stop it?

Upvotes: 1

Views: 1721

Answers (1)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

It's marked as such since the type in the view model is an int.

It's adding the html due to this line:

@Html.HiddenFor(model => model.BidID, new { id="bidItemID" })

Why is it a problem that the extra attributes are present? If it really is problematic, try changing the type of BidId to int? (a nullable int).

Upvotes: 1

Related Questions