将选择列表分配给MVC中动态创建的下拉列表 [英] Assign selectlist to dynamically created dropdown in MVC

查看:32
本文介绍了将选择列表分配给MVC中动态创建的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下静态选择列表

  var listItems = new SelectListItem [] {新的SelectListItem(){Text =-请选择-",Value ="},新的SelectListItem(){Text ="Death",Value ="Death"},新的SelectListItem(){Text ="Resignation",Value ="Resignation"},新的SelectListItem(){Text =退休",Value =退休"},新的SelectListItem(){Text ="Termination",Value ="Termination"},新的SelectListItem(){Text ="Transfer",Value ="Transfer"},};ViewBag.DeletionReason = listItems; 

并将其分配给ViewBag.

现在我必须在页面中搜索员工ID.

例如:1234

然后在下一个视图中列出其职员ID以1234开头的所有职员.在针对每个员工详细信息列出相同内容的同时,我需要列出上述选择列表以选择删除原因.

我做到了如下

控制器

 公共ActionResult DeleteRequest(string [] memberIDs,string []delete_reason,字符串[]有效日期){foreach(memberID中的字符串项){np_user_requests_dtls userRequest = new np_user_requests_dtls();staffid = memberIDs [i];有效日期值=有效日期[i];userRequest.staffid_id =员工ID;userRequest.deletion_reason =删除原因[i];userRequest.effective_date = Convert.ToDateTime(effectiveDateValue);尝试{db.SaveChanges();}抓住(除例外){}}i ++;}} 

查看

 <表>< thead>< tr>< th>员工编号< th>新的有效结束日期</th>< th>删除原因</th>< th><输入type ="checkbox" name ="checkAll" id ="checkAll" value ="1" style ="width:25px"/>< a href ="javascript:void(0);"id ="selectAllInResult">或选择结果中的全部</a>< span id ="span_effective_for_all" style ="display:none"><输入类型=文本" name =有效日期_全部" id =有效日期_全部" value ="占位符=全部有效结束日期" class ="datepicker" style =宽度:150px">& nbsp;<输入type ="button" name ="cancelAll" id ="cancelAll" value =取消" style ="width:60px"/></span>< span id ="span_deletion_reason_all" style ="display:none"><选择name ="deletion_reason_all" id ="deletion_reason_all" style ="width:150px">& nbsp;</select>< input type ="button" name ="cancelAll" id ="cancelAll"值=取消" style ="width:60px"/></span></th></tr></thead>< tbody>@if(Model!= null&& Model.Count()> 0){foreach(模型中的变量项){< tr>< td>@ Html.DisplayFor(modelItem => item.staff_id)</td>< td><输入类型=文本" name =有效日期[]" id ="@(" efddate _"+ @ item.staff_id)" value ="占位符=有效结束日期" class ="datepicker"></td>< td>@ Html.DropDownList("deletion_reason []",(SelectList)@ ViewBag.DeletionReason)</td>< td><输入type ="checkbox" name ="memberIds []" id ="@ item.staff_id" value ="@ item.staff_id_id"/></td></tr>}</tbody></table> 

模型

 公共字符串staff_id {get;放;}公开日期有效日期{放;}公共字符串delete_reason {get;放;} 

在视图中,如果delete_reason也与有效日期这样的文本类型相同,则可以发布数据.但我需要将其下拉.我被困在那里

这给我一个运行时错误

 没有类型为"IEnumerable< SelectListItem>"的ViewData项的键为"deletion_reason []". 

也请给我一个想法,我在发布时如何获取与每个员工相对应的值.

解决方案

首先,您可以将SelectList的创建简化为

  ViewBag.DeletionReason = new SelectList(new List< string>(){"Death","Resignation","Retirement","Termination","Transfer"}); 

注意:请勿包括-请选择-"选项.使用接受 optionLabel (请参阅下文)的 DropDownListFor()的重载.

假设模型名为 Staff ,则视图必须为

  @model列表< yourAssembly.Staff>.....for(int i = 0; i< Model.Count; i ++){@ Html.HiddenFor(m => m [i] .staff_id)@ Html.DisplayForFor(m => m [i] .staff_id)@ Html.TextBoxFor(m => m [i].生效日期,新{@ class ="datepicker"})@ Html.DropDownListFor(m => m [i] .deletion_reason,(SelectList)ViewBag.DeletionReason,-请选择-")} 

而您的POST方法必须为

  [HttpPost]公共ActionResult YourActionName(List< Staff>模型){} 

在视图中使用 for 循环以及强类型帮助程序将确保您使用索引器正确命名表单控件,并且可以将它们绑定到POST方法中的集合./p>

旁注:您在编辑中发布的错误是由于 ViewBag.DeletionReason 的值为 null 引起的.也许是因为您在POST方法中返回了视图,但尚未重新分配 ViewBag.DeletionReason 的值?

I have static select list as below

var listItems = new SelectListItem[] {
                new SelectListItem(){Text="-- Please Select --",Value=""},
                new SelectListItem(){Text="Death",Value="Death"},
                new SelectListItem(){Text="Resignation",Value="Resignation"},
                new SelectListItem(){Text="Retirement",Value="Retirement"},
                new SelectListItem(){Text="Termination",Value="Termination"},
                new SelectListItem(){Text="Transfer",Value="Transfer"},
            };

            ViewBag.DeletionReason = listItems;

and assigning the same to ViewBag.

Now in my page i have to search for a staff ID.

eg: 1234

then in next view all the staffs whose staff id starts with 1234 will be listed. While listing the same against each staff details i need to list the above select list for choose there deletion reason.

I done it as below

Controller

    public ActionResult DeleteRequest(string[] memberIDs,string[] 
deletion_reason, string[] effective_date)
     {
    foreach (string item in memberIDs)
{

  np_user_requests_dtls userRequest = new np_user_requests_dtls();
  staffid = memberIDs[i];
  effectiveDateValue = effective_date[i];
  userRequest.staffid_id = staffid;
  userRequest.deletion_reason = deletion_reason[i];
userRequest.effective_date = Convert.ToDateTime(effectiveDateValue);

try
 {
   db.SaveChanges();

 }
  catch (exception ex)
                        {

                        }
                    }

                    i++;
                }

            }

View

<table >
<thead>
<tr>
<th>
Staff ID
<th>
New Effective End Date
</th>
<th>
Deletion Reason
</th>
<th>
<input type="checkbox" name="checkAll" id="checkAll" value="1" style="width: 25px" />
<a href="javascript:void(0);" id="selectAllInResult"> Or  Select all in result</a>
<span id="span_effective_for_all" style="display:none">
<input type="text" name="effective_date_all" id="effective_date_all" value="" placeholder="Effective End Date All" class="datepicker" style="width: 150px" >&nbsp;<input type="button" name="cancelAll" id="cancelAll" value="Cancel" style="width: 60px" />
</span>
<span id="span_deletion_reason_all" style="display:none">
<select name="deletion_reason_all" id="deletion_reason_all" style="width: 150px">&nbsp;</select><input type="button" name="cancelAll" id="cancelAll" value="Cancel" style="width: 60px" />
</span>
</th>
</tr>
</thead>
<tbody>
 @if (Model != null && Model.Count() > 0)
{
foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.staff_id)
</td>
<td>
<input type="text" name="effective_date[]" id="@("efddate_"+@item.staff_id)"  value="" placeholder="Effective End Date" class="datepicker"></td>
<td>
@Html.DropDownList("deletion_reason[]",(SelectList)@ViewBag.DeletionReason)
</td>
<td>
<input type="checkbox" name="memberIds[]" id="@item.staff_id" value="@item.staff_id_id" />
</td>
</tr>
}
</tbody>
</table>

Model

public string staff_id { get; set; }
public date effective_date { get; set; }
public string deletion_reason { get; set; }

In the view if the deletion_reason is also same as text type like effective_date I am able to post the data. But I need it to be dropdown. I am stucked there

This is giving me a run time error

 There is no ViewData item of type 'IEnumerable<SelectListItem>' 
that has the key 'deletion_reason[]'.

Also please give an idea how can i get the value corresponding to each staff while posting.

解决方案

Firstly you can simplify your SelectList creation to

ViewBag.DeletionReason = new SelectList(new List<string>() { "Death", "Resignation", "Retirement", "Termination", "Transfer" });

Note: Do not include the "--Please select--" option. Use the overload of DropDownListFor() that accepts optionLabel (refer below).

Assuming the model is named Staff then the view needs to be

@model List<yourAssembly.Staff>
.....
for(int i = 0; i < Model.Count; i++)
{
  @Html.HiddenFor(m => m[i].staff_id)
  @Html.DisplayForFor(m => m[i].staff_id)
  @Html.TextBoxFor(m => m[i].effective_date, new { @class="datepicker" })
  @Html.DropDownListFor(m => m[i].deletion_reason, (SelectList)ViewBag.DeletionReason, "-- Please Select --")
}

and you POST method needs to be

[HttpPost]
public ActionResult YourActionName(List<Staff> model)
{
}

The use of the for loop in the view, in conjunction with the strongly typed helpers will ensure you form controls are correctly named with indexers and can be bound to a collection in the POST method.

Side note: The error you have posted in your edit is caused by the value of ViewBag.DeletionReason being null. Perhaps because you return the view in the POST method but have not reassigned the value of ViewBag.DeletionReason?

这篇关于将选择列表分配给MVC中动态创建的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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