MVC 3绑定模型属性为2字段(例如其他标题) [英] MVC 3 Bind Model property to 2 fields (e.g. Other Title)

查看:105
本文介绍了MVC 3绑定模型属性为2字段(例如其他标题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要达到一个非常常见的场景,而给出的选项可供选择列表中,最后一个说:其他,并选中当用户在输入字段psented $ P $指定哪些其他是。

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 = GT; m.Title,新的SelectList(Model.TitleList),请选择...)@ Html.TextBoxFor(M = GT; m.Title )

我希望模型时,其他中的DropDownLis选择文本框的值绑定,而在其它情况下绑定到所选项目的DropDownList。

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?

推荐答案

一个更好的解决办法是的不可以绑定到两个领域,而是复制选定从下拉项与一些绑定文本框聪明的javascript:

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:

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

这篇关于MVC 3绑定模型属性为2字段(例如其他标题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆