简体   繁体   English

使用参数从视图调用操作

[英]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. 您必须通过javascript(无论是标准的还是jQuery)来做到这一点。

There are many examples here on SO of this type of functionality, search for $ajax and mvc textbox value. 在SO上有很多此类功能的示例,搜索$ ajax和mvc文本框值。

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) : 这是一个示例,向您展示如何执行此操作(从视图中调用AddPerson方法):

The view "AddPerson" 视图“ 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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