MVC 3 Bind Model property to 2 fields (e.g. Other Title)

泄露秘密 提交于 2019-12-11 05:28:16

问题


I'm trying to achieve a very common scenario whereas given a list of options to choose from, the last one says "Other" and when selected the user is presented with the input field to specify what "other" is.

In my case, it's a list of Person's titles:

public List<string> TitleList
{
    get
    {
        return new List<string> { "Mr", "Mrs", "Miss", "Dr", "Other" };
    }
}

and what I'm trying to do is this:

@Html.DropDownListFor(m => m.Title, new SelectList(Model.TitleList), "Please select...") @Html.TextBoxFor(m => m.Title)

I want the model to bind the TextBox value when "Other" is selected in the DropDownLis, and bind to selected item in DropDownList in all other cases.

Is this achievable without adding an extra property on the Model?


回答1:


a better solution is not to bind to two fields, instead, copy selected item from a drop-down into bound textbox with some clever javascript:

@Html.DropDownList("ddlTitle", new SelectList(Model.TitleList), "Please select")
@Html.TextBoxFor(m => m.Title, new { maxLength = 10 })

Javascript:

ToggleTitleFields = function () {
    var title, txtTitle;
    title = $('select#ddlTitle').val();
    txtTitle = $('input#Title');
    if (title === "Other") {
        txtTitle.val("");
        txtTitle.show();
        return txtTitle.focus();
    } else {
        txtTitle.hide();
        txtTitle.val(title);
        return $('span[data-valmsg-for="Title"]').empty();
    }
};

$(document).on("change", "select#ddlTitle", function(e) {
    return ToggleTitleFields();
});

hope this helps somebody




回答2:


found a client-side solution: add/remove the "name" attribute from DropDownList. Here's my coffee script:

ToggleTitleFields = () ->
    if $('select#Title').val() == "Other"
        $('select#Title').removeAttr('name')
    else
        $('select#Title').attr('name','Title')



回答3:


Tsar,

Being honest, this isn't a scenario that I've had to deal with before, but is nonetheless a good one. If I were faced with this dilemma and was allowed to use a javascript solution, i'd present a previously 'hidden' textbox when other was chosen. The user would then have to enter the new value into this texbox, which on loosing focus would populate the selectlist and be selected. Then when the form was submitted, you'd have this new value still as part of the exisiting model.

Of course, you could also do a similar logic of showing the textbox when selecting other but this time, do a little logic on the httpost controller action to determine if the 'other' item was selected and then populate the model from the 'textbox' value.

Of course, both scenarios would need a heap of validation, but in principle, either approach would 'work'



来源:https://stackoverflow.com/questions/10797721/mvc-3-bind-model-property-to-2-fields-e-g-other-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!