如何从MVC中的formcollection对象检索文本 [英] How to retrieve text from formcollection object in MVC

查看:108
本文介绍了如何从MVC中的formcollection对象检索文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

formcollection对象中的值存储为键值对.但是,假设有人使用"Id"作为值,并使用"Name"作为文本来填充下拉列表.在那种情况下,如何使用formcollection对象从下拉列表中访问名称"?

The values in formcollection object are stored as Key-value pairs. But, suppose somebody uses "Id" as the value and "Name" as the text to populate a dropdownlist. In that case, how can one access "Name" from the dropdownlist using formcollection object?

要访问选定的值,我知道以下代码:

To access the selected value, I know this code:

public ActionResult ActionName(FormCollection formcollection)
{
   var value = formcollection["dropdownlistName"];
}

上面的代码将给出"Id"的值,但是如果我需要检索"Name"并将其存储在变量中怎么办?

The above code will give the value which is "Id", but what if I need to retrieve "Name" and store it in a variable?

我是新手;如果有人知道,请帮助.您的帮助将不胜感激.谢谢.

I am a novice; if somebody knows, please help. Your help will be appreciated. Thanks.

推荐答案

您不能将下拉列表文本发布到服务器,只能发送值.有解决方法-您可以手动发布数据并添加下拉文本.但是,正确的方法是首先从填充下拉列表的源中引用id.

You cannot post the drop down list text to the server, you can only sent the values. There are workarounds -- you can POST the data manually and add the dropdown text along with it. But the proper way to do it is to refer back the id from the source you filled the drop down list in the first place.

示例:

如果您的下拉菜单如下:

If you have a drop down like this:

<form id="someForm">
<select id="country" name="countryddl">
    <option value="1">US</option>
    <option value="2">UK</option>
</select>
<input type="submit" value="submit"/>
</form>

在控制器中获取值并将其映射回源.

Get the value in the controller and map it back to the source.

public ActionResult ActionName(FormCollection formcollection)
{
   var countryId = formcollection["countryddl"];
   var countryName = countriesMap[countryId ]; // Assuming countriesMap is a dictionary with all countries mapped to its Id.

}

解决方法

如果绝对必须在表单中发送文本,则可以覆盖表单提交时的默认行为,并将下拉文本和值一起发布:

If you absolutely must send the text along in the form, you can override the default behaviour on form submitting and post the dropdown text along with the value:

$("#btnSubmit").click(function(e){
    e.preventDefault();

    var selectedOption = $("#CountryId option:selected").text();
    // Add the selected drop down text to a hidden field
    $("<input/>",{type:'hidden',name:'countryName'}).val(selectedOption).appendTo("#someForm");
    // now post the form 
    $("#someForm").submit();
});

现在,您可以像这样在控制器中获取选定的文本:

Now you can get the selected text in your controller like this:

var countryName = formcollection["countryName"];

这篇关于如何从MVC中的formcollection对象检索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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