Sina Razavi
Sina Razavi

Reputation: 45

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?

Upvotes: 0

Views: 846

Answers (1)

Oasis
Oasis

Reputation: 478

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();
}

Upvotes: 1

Related Questions