[c#] ASP.NET MVC get textbox input value

I have a textbox input and some radio buttons. For example my textbox input HTML looks like that:

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

Once user clicks a button on a web page I want to pass data to my controller:

<input type="button" name="Add" value="@Resource.ButtonTitleAdd"  onclick="location.href='@Url.Action("Add", "Configure", new { ipValue =@[ValueOfTextBox], TypeId = 1 })'"/>

Maybe it is trivial but my problem is that I do not know how to get textbox value and pass it through to the controller. How can I read the textbox value and pass it to the controller through ipValue=@[ValueOfTextBox]?

This question is related to c# html asp.net-mvc asp.net-mvc-4 razor

The answer is


you can do it so simple:

First: For Example in Models you have User.cs with this implementation

public class User
 {
   public string username { get; set; }
   public string age { get; set; }
 } 

We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this

public ActionResult Add()
{
  var model = new User();
  return View(model);
}

When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:

@model MyApp.Models.Student
@using (Html.BeginForm()) 
 {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.username, htmlAttributes: new { 
                           @class = "control-label col-md-2" })
            <div class="col-md-10">
                 @Html.EditorFor(model => model.username, new { 
                                 htmlAttributes = new { @class = "form-
                                 control" } })
                 @Html.ValidationMessageFor(model => model.userame, "", 
                                            new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, htmlAttributes: new { @class 
                           = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = 
                                new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.age, "", new { 
                                           @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" 
                 />
            </div>
        </div>
   </div>
}

So on button submit you will use it like this

[HttpPost]
public ActionResult Add(User user)
 {
   // now user.username has the value that user entered on form
 }

Try This.

View:

@using (Html.BeginForm("Login", "Accounts", FormMethod.Post)) 
{
   <input type="text" name="IP" id="IP" />
   <input type="text" name="Name" id="Name" />

   <input type="submit" value="Login" />
}

Controller:

[HttpPost]
public ActionResult Login(string IP, string Name)
{
    string s1=IP;//
    string s2=Name;//
}

If you can use model class

[HttpPost]
public ActionResult Login(ModelClassName obj)
{
    string s1=obj.IP;//
    string s2=obj.Name;//
}

You may use jQuery:

<input type="text" name="IP" id="IP" value=""/>
@Html.ActionLink(@Resource.ButtonTitleAdd, "Add", "Configure", new { ipValue ="xxx", TypeId = "1" }, new {@class = "link"})

<script>
  $(function () {
    $('.link').click(function () {
      var ipvalue = $("#IP").val();
      this.href = this.href.replace("xxx", ipvalue);
    });
  });
</script>

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC