ASP.Net根据EF模型返回的值选择一个下拉选项(在视图中)

时间:2019-04-29 18:32:06

标签: c# asp.net-mvc-5 entity-framework-6

对于视图中的下拉列表(作为SelectList),我可以成功地将值设置为模型返回的ID,但是列表不会更新以将所选ID反映为所选项目。

<%var type = Model.CompanyTypeId; %>
<%= Html.DropDownList("Type", (ViewData["Types"] as SelectList),
        new Dictionary<string, object>()
            {
                { "class", "form-control form-input"},
                { "Id", "CoType"},
                { "Name", "CoType"},
                { "value", type },
                { "option", "selected" }
             })%>

我希望下拉列表将选定的项目更新为相应的ID

(在ChromeDev工具中,我可以验证Id = Model.CompanyTypeId和option =“ selected”,但下拉列表仍会显示默认情况下选中的项目。

我希望下拉列表将所选项目更新为相应的ID

(在ChromeDev工具中,我可以验证Id = Model.CompanyTypeId和option =“ selected”,但下拉列表仍会显示默认情况下选中的项目。

    <select id="CoType" name="CoType" class="form-control form-input" 
     option="selected" value="1">
        <option value="-1">- Assign Type - </option>
        <option value="1">Dummy</option>
        <option value="2">Test CompanyType</option>
    </select>

1 个答案:

答案 0 :(得分:1)

由于您已经拥有import subprocess import sys import PySimpleGUI as sg """ Demo Program - Realtime output of a shell command in the window Shows how you can run a long-running subprocess and have the output be displayed in realtime in the window. """ def main(): layout = [ [sg.Text('Enter the command you wish to run')], [sg.Input(key='_IN_')], [sg.Output(size=(60,15))], [sg.Button('Run'), sg.Button('Exit')] ] window = sg.Window('Realtime Shell Command Output', layout) while True: # Event Loop event, values = window.Read() # print(event, values) if event in (None, 'Exit'): break elif event == 'Run': runCommand(cmd=values['_IN_'], window=window) window.Close() def runCommand(cmd, timeout=None, window=None): """ run shell command @param cmd: command to execute @param timeout: timeout for command execution @param window: the PySimpleGUI window that the output is going to (needed to do refresh on) @return: (return code from command, command output) """ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = '' for line in p.stdout: line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip() output += line print(line) window.Refresh() if window else None # yes, a 1-line if, so shoot me retval = p.wait(timeout) return (retval, output) main() ,因此可以轻松使用Model.CompanyTypeId。您无需在HTML属性上设置值。

控制器

Html.DropDownListFor

查看

public ActionResult Index()
{
    var model = new TestModel
    {
        CompanyTypeId = 1
    };

    ViewBag.Types = new List<SelectListItem>
    {
        new SelectListItem { Value = "-1", Text = "-- Assign Type --" },
        new SelectListItem { Value = "1", Text = "Dummy" },
        new SelectListItem { Value = "2", Text = "Test" },
    };

    return View(model);
}