【问题标题】:How can I fetch the mvc model dynamically on a jquery event handler?如何在 jquery 事件处理程序上动态获取 mvc 模型?
【发布时间】:2020-12-04 14:22:10
【问题描述】:

我正在使用 asp.net 核心和 MVC 架构。我在单击按钮时有一个 jquery 事件处理程序。如果用户单击按钮,我会根据从 c# 模型中获取的数据对 DOM 应用不同的更改。 我需要的模型数据会根据用户输入而变化。但由于事件处理程序仅在启动时执行,因此其中的模型数据反映了模型的初始状态。

我的javascript:

    $(document).on("click", ".edit-log-child", function () {
            var NameCategory = $(this).data('id');

            /*some DOM change*/

            var json = @Json.Serialize(@Model.Categories);
            if (JSON.stringify(json) != JSON.stringify("{[]}"))
            {
                 var currentCategory = json.find(element => element.name == NameCategory);
                 ProcessEditCategorie(currentCategory);

            }

        });

有没有办法从我的 javascript 函数/事件处理程序中获取我当前的模型?

【问题讨论】:

  • 您可以从后端提供的 json API 获取更新数据。您可以使用 JQuery Ajax 请求调用它,将数据发布到后端并根据它返回相关数据。看这里例如stackoverflow.com/q/59325946/6568785 另外,您可能不应该在 click 事件中硬编码初始模型,而应该在那里有 ajax 请求。

标签: javascript c# jquery asp.net-core-mvc


【解决方案1】:

您可以使用表单发布或ajax:

1.form post(提交表单到action,action返回一个包含你想要的数据的视图):

查看(GetData1.cshtml):

@model IEnumerable<string>
<form method="post">
    <input name="id" id="id"/>
    <input type="submit" value="submit" />
</form>

行动:

public IActionResult GetData1(string id) {
            List<string> l = new List<string> { "a", "b", "c" };
            return View(l);
        }

结果: 2.ajax(点击按钮时,从action中获取数据,不会刷新页面):

查看(GetData1.cshtml):

    <input name="id" id="id"/>
<button onclick="getdata()" >submit</button>
<script>
        function getdata() {
           $.ajax({
                    type: "POST",
                url: '@Url.Action("GetData2", "Test")',
                data: { "id": $("#id").val() }
                 }).done(function (data) {

                });
        }
    </script>

动作(TestController):

public List<string> GetData2(string id)
    {
        List<string> l = new List<string> { "a", "b","c" };
        return l;
    }

结果:

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多