Post ID doesn't Work in Form

2019-08-28 11:06发布

问题:

I have a post where I define a new database entity. After user enters needed values and submits the form, I insert the entity and post it back to the same page and display it's ID. When I enter the ID area disabled and readonly as below, it works perfectly.

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>

    ID:
    @Html.TextBoxFor(model => model.ID, new { disabled = "disabled", @readonly = "readonly" })

    <p><input type="submit" name="submit" value="Create" /></p>
    </fieldset>
}

However, when I enter it only readonly as in below, it does insert the entity, but doesn't view the ID.

@Html.TextBoxFor(model => model.ID, new { @readonly = "readonly" })

I have another submit in the form, which uses the entities ID. However, I cannot use disabled here with the ID area, as it doesn't post the ID value. What can I do to resolve the issue?

回答1:

You can enable the disabled field just before submitting. So, keep the ID field disabled. Now, enable it on submit. ie; if you submit the form on "myButton" click, add this in document.ready():

$('#myButton').click(function(e)
{
    e.preventDefault();
    $("#ID").removeAttr('disabled');
    $('form').submit();
});


回答2:

Instead of using html extensions, I directly wrote:

<input type="text" name="ID" value="@Model.ID" readonly />

And it works like a charm.