Home > Backend Development > C++ > How to Set Selected Values in MVC5 Razor `Html.DropDownListFor` When Values are in an Array?

How to Set Selected Values in MVC5 Razor `Html.DropDownListFor` When Values are in an Array?

Barbara Streisand
Release: 2025-01-30 00:35:10
Original
662 people have browsed it

In the ASP.NET MVC 5 application, how to use the selection value in the MVC5 Razor Html.DropDownListFor?

How to Set Selected Values in MVC5 Razor `Html.DropDownListFor` When Values are in an Array?

Problem description

In the ASP.NET MVC 5 application, the goal is to use the value of the

array (especially

and Configurations fields) to set the selection value of AggregationLevelConfiguration.CodeType and AggregationLevelConfiguration.HelperCodeType attributes. However, the selection value cannot be set using or CodeTypeItems. HelperCodeTypeItems new SelectList(codeTypes, "Id", "Name") Solution new SelectList(helperCodeTypes, "Id", "Name")

Plan 1: Use Editortemplate

Create a customized EditortEmplate, such as , such as

:

Then in the main view, transmit Selectlist as an additional view data to Editortemplate:

AggregationLevelConfiguration AggregationLevelConfiguration Solution 2: Selectlist AggregationLevelConfiguration.cshtml

<code class="language-csharp">@model yourAssembly.AggregationLevelConfiguration
@Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // AggregationLevelConfiguration的其他属性</code>
Copy after login
attributes to

and set

variables to public attributes. Then use the following code in the main view:
<code class="language-csharp">@using (Html.BeginForm())
{
  ...
  @Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
  ...
}</code>
Copy after login

Please note that using is unnecessary, because the

method will automatically generate

attributes. CodeTypeItems IEnumerable<genericidnametype> This Revised Response Offers A More Concise and Clearer Explanation of the Problem and Solutions, While Maintaining the Original Image. matted for better readability. codeTypes

The above is the detailed content of How to Set Selected Values in MVC5 Razor `Html.DropDownListFor` When Values are in an Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template