简体   繁体   中英

How can I get value of textbox or dropdownlist and send to database in ASP.NET MVC4

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 :

@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”

How do this?

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

Note : Your controls should have have names (just having an id is not returning values in the 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM