簡體   English   中英

使用參數從視圖調用操作

[英]Calling action from view with parameters

我有一個文本框和一個按鈕,單擊該按鈕時,我想從控制器調用一個動作,並將文本框值作為參數傳遞。 那我該怎么辦呢?

您必須通過javascript(無論是標准的還是jQuery)來做到這一點。

在SO上有很多此類功能的示例,搜索$ 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.');
      }
    });    
});

[編輯] -根據用例(您未指定),您當然可以將文本框包裝在表單標簽內,然后以“常規”方式提交,從而捕獲文本框“名稱”和“值”在動作的形式集合中。

在通常情況下,取決於您要確切執行的操作,建議您將視圖強類型化(針對模型),並在視圖中使用表單。 這是一個示例,向您展示如何執行此操作(從視圖中調用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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM