简体   繁体   中英

Calling action from view with parameters

I have a textbox and a button, when the button is clicked, i want to invoke an action from the controller and pass the textbox value as a parameter. So how can I do that?

you'll have to do this via javascript, be that standard or more likely, jQuery.

There are many examples here on SO of this type of functionality, search for $ajax and mvc textbox value.

example:

$(function () {
    var txtBoxValue = $('#yourTextboxId').val();
    $.ajax({
      url: '@Url.Action("Youraction", "Yourcontroller")',
      data: { id: txtBoxValue },
      success: function(data) {
        $('.result').html(data);
        alert('Load was performed.');
      }
    });    
});

[Edit] - depending on the usecase (which you don't specify), you could of course wrap the textbox inside a form tag and just submit it in the 'normal' fashion, thereby capturing the textbox 'name' and 'value' inside the formcollection of the action.

Depends on what exactely you want to do, in the ordinary cases, I suggest you make your view strongly typed (to your model), and use a form in your view. Here is an example that show you how to do it (Call the AddPerson method from the view) :

The view "AddPerson"

@model MvcApplication.Models.Person
//You can pass in the actionName and the controllerName as parameters to the method BeginForm()
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
}

The action in the "Person" Controller

[HttpPost]
public ActionResult AddPerson(Person person)
{
    // The code
    return View("OperationEndWithSuccess");
}

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