简体   繁体   中英

How to pass textbox value to controller

I have a textbox like below

   @using (Html.BeginForm("checkUserType", "Place", new {type =  }))
    {
        <div id="login">
            <div class="userNameLabel">UserName</div>
            <div class="userNameField"><input type="text" id="txtUserName"/><span><input type="button" value="ok" id="ok" /></span></div>
        </div>
    }

I want to pass the textbox value to my controller. For that I used the below code, but it's not working... Pls help...

Action method

[HttpPost]
        public ActionResult checkUserType(string type)
        {
            var elements = from element in db.USERS
                           where element.UserType == type
                           select element;
            if (elements == null)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("Place/Index");
            }
        }

尝试一次

window.location.href = '@Url.Action( "checkUserType", "Place" )?type='+type

Try This

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<% Html.BeginForm("Search", "Employee");%>
<table>
   <tr>
    <td>
        Name:
    </td>
    <td>
        <input type="text" id="SearchText" name="SearchText" style="width: 325px" />
    </td>
    <td> 
    </td>
    <td>
        <input type="submit" id="Search" value="Search" />
    </td>
</tr>
</table>
<% Html.EndForm();%>

your action goes like this...

public ActionResult Search(string searchText)
{ 
 }

Hope it helps you

MVC will map your names of inputs to parameters of your method.

However, your current input doesn't specify a name:

<input type="text" id="txtUserName"/>

So add that:

<input type="text" name="type" id="txtUserName"/>

And it will map to the parameter. And take away the anonymous object from the BeginForm since that value will be provided by the input field, so doen't need to be in the form 's action.

I just update your code try this

 @using (Html.BeginForm("checkUserType", "Place"))
    {
        <div id="login">
            <div class="userNameLabel">
                UserName</div>
            <div class="userNameField">
                <input type="text" id="txtUserName" name="UserName" /><span><input type="submit" value="ok" id="ok" /></span></div>
        </div>
    }

and controller

 public ActionResult checkUserType(string UserName)
        {
 string _data = UserName;


        }

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