使用参数从视图调用操作

时间:2012-08-08 11:31:04

标签: javascript jquery asp.net-mvc-3

我有一个文本框和一个按钮,当单击该按钮时,我想从控制器调用一个动作并将文本框值作为参数传递。那我怎么能这样做呢?

2 个答案:

答案 0 :(得分:0)

你必须通过javascript,这个标准或更可能的jQuery来做到这一点。

此处有很多关于此类功能的示例,搜索$ ajax和mvc文本框值。

示例:

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

[编辑] - 根据用例(您未指定),您当然可以将文本框包装在表单标记中,然后以“正常”方式提交,从而在动作的formcollection中捕获文本框'name'和'value'。

答案 1 :(得分:0)

取决于你想要做什么,在一般情况下,我建议你强烈地键入你的视图(对你的模型),并在你的视图中使用一个表单。这是一个向您展示如何操作的示例(从视图中调用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>
}

“人物”控制器中的操作

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