makertoo
makertoo

Reputation: 166

Razor: Transfer input text + Model to a controller

Hy everybody, In my Razor View page, I have a text input. I want to call a controller by using the "onchange" event and add my input value to a list contained in my Razor Model.

This is my html page:

<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>

This is my called controller action :

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);
        }

I add the input text value to the list in my controller action. The problem is that input is always '==null' (because there is no submit). However, it works when I press the Enter keyboard button.

Help, please Thks in advance

Upvotes: 0

Views: 148

Answers (1)

Greenonion
Greenonion

Reputation: 87

You could do something like this:

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

i.e. made AJAX call when you need and then refresh your view.

Upvotes: 0

Related Questions