【问题标题】:Update Model property from Controller in Asp.Net MVC从 Asp.Net MVC 中的控制器更新模型属性
【发布时间】:2019-11-01 09:15:42
【问题描述】:

我有一个 HTML dropdownList 当前显示来自模型的数据,现在对于一些操作我想更改 dropdownList 内容。我想如果我更新模型,它也会反映到视图中。下面是我的模型代码

视图模型

public class CaseAssignmentRuleSetViewModel
    {
        public CaseAssignmentRuleSetViewModel()
        {

        }
       public int id { get; set; }
       public string name { get; set; }
       public Dictionary<string, string> AssignmentUsers { get; set; }
    }

所以在viewModel 中,它的dictionarydropdownList 的来源,如下所示。

查看

<select name="assignmentTeam" class="form-control case-assignment-use-type-value2" placeholder="Select a User">


            @foreach (string key in Model.AssignmentUsers.Keys)
            {
                <option value="@key">@Model.AssignmentUsers[key]</option>
            }
        </select>

最后经过一些操作后,我使用 JQuery 函数将新列表返回到我的 Controller 方法,如下所示。

控制器

 [HttpPost, Route("CaseAssignmentRuleSet/ListofAssignees", Name = "ListofAssignees")]
        public List<string> SetListofAssignees(string [] listOfAssignedroles)
        {
            CaseAssignmentRuleViewModel caseAssignmentRuleViewModel = new CaseAssignmentRuleViewModel();
            List<string> listOfAssignees = new List<string>();
            if (listOfAssignedroles!= null)
            {
                listOfAssignees = new List<string>(listOfAssignedroles);
            }

            return listOfAssignees;             

        }

如何使用新的项目列表更新我的dropdownList

【问题讨论】:

    标签: c# asp.net-mvc model-view-controller html-select html.dropdownlistfor


    【解决方案1】:

    因此,当您说您正在使用 jquery 函数重新获得新列表时,我假设您正在做的是对您的控制器进行 ajax 调用。

    如果是这样,那么在您完成的 ajax 调用函数中,清除当前列表,然后遍历您的新列表添加新选项:(伪代码)

    $.ajax( '/CaseAssignmentRuleSet/ListofAssignee' )
     .done(function(data) {
    
       //get the select element, you should really add an ID to the element to select instead of name but whatever
       var $el = $('[name=assignmentTeam]');
    
       //clear the current select list options
       $el.empty();
    
       //iterate through your new options and add them to the select list
       $.each(data, function(key,value) {
        $el.append($("<option></option>").attr("value", value).text(value));
     });
    }).fail(function() {alert( "error" );}).always(function() {//alert( "complete" );});
    

    【讨论】:

    • 其实我并没有直接绑定返回的列表,控制器端有更多的处理。所以我必须将处理后的数据绑定到下拉列表。
    猜你喜欢
    • 1970-01-01
    • 2013-02-25
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多