如何获取textbox或dropdownlist的值并发送到ASP.NET MVC4中的数据库

时间:2022-12-02 09:59:39

I have a dropdownlist like this:

我有一个这样的下拉列表:

var Country = new List<ListItem> 
{ 
        new ListItem { Text = "American" }, 
        new ListItem { Text = "British" } ,
        new ListItem { Text = "Spanish" }, 
        new ListItem { Text = "Persian" } ,
        new ListItem { Text = "China" },
        new ListItem { Text = "else" }
};
@Html.DropDownList("Country", new SelectList(Country))

When a user choose “else” , one textbox appears and user can type it’s country on textbox, I did this by jquery :

当用户选择“else”时,会出现一个文本框,用户可以在文本框中键入它的国家/地区,我通过jquery执行此操作:

@Html.TextBox ("txtCountry",null,new {@id="txtCountry"})

I want to define a variable to get Country from user and send to database. Filed’s name in Model is “Country”

我想定义一个变量来从用户获取Country并发送到数据库。模型中提交的名称是“国家”

How do this?

这是怎么回事?

1 个解决方案

#1


1  

You can get the list of form controls values using FormCollection Class. Try the below option

您可以使用FormCollection类获取表单控件值列表。请尝试以下选项

Note : Your controls should have have names (just having an id is not returning values in the formCollection)

注意:您的控件应该有名称(只是id没有返回formCollection中的值)

[HttpPost]
public ActionResult YourActionMethod(FormCollection Collection)
{
        string Country = string.Empty;

        if (Collection["txtCountry"] != null)
            Country = Collection["txtCountry"].ToString();
//Else you can assign the values to your model object.
        return View();
}

#1


1  

You can get the list of form controls values using FormCollection Class. Try the below option

您可以使用FormCollection类获取表单控件值列表。请尝试以下选项

Note : Your controls should have have names (just having an id is not returning values in the formCollection)

注意:您的控件应该有名称(只是id没有返回formCollection中的值)

[HttpPost]
public ActionResult YourActionMethod(FormCollection Collection)
{
        string Country = string.Empty;

        if (Collection["txtCountry"] != null)
            Country = Collection["txtCountry"].ToString();
//Else you can assign the values to your model object.
        return View();
}