Razor:将输入文本+模型传输到控制器

Razor: Transfer input text + Model to a controller

本文关键字:模型 传输 控制器 文本 输入 Razor      更新时间:2023-09-26

大家好,在我的Razor View页面中,我有一个文本输入。我想使用"onchange"事件调用一个控制器,并将我的输入值添加到Razor模型中包含的列表中。

这是我的html页面:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>MyForms</title>
</head>
<body>
    <label>Code</label>
    <form method="post" action="">
        <input name="NPItem" maxlength="11" autofocus  onkeypress="return isNumberKey(event)"     onchange="location.href = '@Url.Action("addtoList", "MyController", new { formsData =     Newtonsoft.Json.JsonConvert.SerializeObject(Model) })';"/>
    </form>
    <table border="1" id="listeNPAI">
        <tr>
            <th>Index</th>
            <th>Value</th>
        </tr>
        @{
            foreach (Tuple<string, string> item in Model.list) {
                <tr>
                    <td>@item.Item1</td>
                    <td>@item.Item2</td>
                </tr>
            }
        }
    </table>
</body>
</html>

这就是我所谓的控制器动作:

public ActionResult addtoList(string formsData) {
            formsData _form = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelClass>(formsData);
            string input = Request["NPItem"];
            if (input == null) { input = ""; } else { input = input.Trim(); }
            if (input.Length == 11) {
                _form.list.Add(new Tuple<string, string>(input.Substring(0, 5), input.Substring(6)));
            }
            return View("FormulaireNPAI", _form);
        }

我在控制器操作中将输入文本值添加到列表中。问题是输入总是"==null"(因为没有提交)。但是,当我按下Enter键盘按钮时,它可以工作。

救命提前Thks

您可以这样做:

$("#element").on("click", function() {
            $.ajax({
                url: "action",
                type: "GET",
                data: { data }
            })
            .done(function(partialViewResult) {
                $("#yourViewWrapper").html(partialViewResult);
            });
        });

即在需要时调用AJAX,然后刷新视图。