Model Binding With Disabled Textbox

前端 未结 7 1992
余生分开走
余生分开走 2020-12-09 07:23

I have a textbox that I am defining as

<%= Html.TextBox(\"Username\", Model.Form.Username, 
        new { @class = \"textbox\", @disabled = \"disabled\" }         


        
相关标签:
7条回答
  • 2020-12-09 07:51

    Easiest way to submit disabled fields is to copy them over to an invisible, non disabled control before submit. Some people create those controls manually and hook up to the on change event in jQuery to copy them on demand, but this solution below is generic, easy and less chatty - although one rule: you must create (render) a clean page after postback (so

    $('#submitBtn').closest('form').one('submit', function() {
    
        var $form = $(this);
    
        // input, textarea, select, option, ----- button, datalist, keygen, output, optgroup
        $form.find('input:disabled, textarea:disabled, select:disabled, option:disabled').each(function () {
    
            var $item = $(this);
    
            var hiddenItem = $item.clone();
            hiddenItem.removeAttr('id');
            hiddenItem.removeAttr('disabled');
            hiddenItem.attr('style', 'display: none');
    
            $item.after(hiddenItem);
        });
    
    });
    
    0 讨论(0)
  • 2020-12-09 07:52

    As suggested in the comments, readonly instead of disabled can be an option but it will not work for select boxes. Instead of creating a hidden input, you can keep the inputs or selects as disabled and still pass the data by changing the disabled property with JavaScript at the submit.

    Using jQuery it'd look like this:

    $('form').on('submit', function(){
        $('input, select').prop('disabled',false);
        return true;
    });
    
    0 讨论(0)
  • 2020-12-09 07:53

    If you want the value to be sent back, but not be editable, consider placing it in a hidden field. Obviously, don't do this for anything that requires a degree of security, since a user can tamper with it.

    0 讨论(0)
  • 2020-12-09 07:55

    use readonly - will disable input but you'll still have it in the binding. You could apply a style on the div to make it looked greyed out maybe?

    <div class="editor-label">
      @Html.LabelFor(model => model.FileName)
    </div>
    <div class="editor-field-greyed-out">
      @Html.TextBoxFor(model => model.FileName, new { @readonly = true })
      @Html.ValidationMessageFor(model => model.FileName)
    </div>
    
    0 讨论(0)
  • 2020-12-09 07:57

    You can do a workaround by adding a hidden field with the same value ;)

    <%= Html.Hidden("Username", Model.Form.Username)%>
    
    0 讨论(0)
  • 2020-12-09 08:07

    I believe a form field that is disabled does not submit anything. If you have a form and disable the foo field in that form, when you post the post will not have the value for the foo field. This is simply the nature of disabling a field in HTML and is not a MVC issue.

    0 讨论(0)
提交回复
热议问题