简体   繁体   English

如何在 jquery 事件处理程序上动态获取 mvc model?

[英]How can I fetch the mvc model dynamically on a jquery event handler?

I'm using asp.net core and MVC architecture.我正在使用 asp.net 内核和 MVC 架构。 I have a jquery event handler on a button click.我在单击按钮时有一个 jquery 事件处理程序。 If the user click the button, I apply different change to the DOM, based on data I fetch from my c# model.如果用户单击按钮,我将根据从 c# model 获取的数据对 DOM 应用不同的更改。 The data I need from my model change depending on user input.我需要的 model 中的数据会根据用户输入而变化。 But as the event handler is only executed at launch time, the data from my model in it reflect the initial state of my model.但由于事件处理程序仅在启动时执行,我的 model 中的数据反映了我的 model 的初始 state。

My javascript:我的 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);

            }

        });

Is there a way to fetch my current model from my javascript function/event handler?有没有办法从我的 javascript 函数/事件处理程序中获取我当前的 model ?

You can use form post or ajax:您可以使用表单帖子或 ajax:

1.form post(submit the form to action,and action return a view with the data you want): 1.form post(提交表单到action,action返回一个包含你想要的数据的视图):

view(GetData1.cshtml):视图(GetData1.cshtml):

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

action:行动:

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

result:结果: 在此处输入图像描述 2.ajax(when button click,get data from action and will not refresh page): 2.ajax(当按钮点击时,从动作中获取数据并且不会刷新页面):

view(GetData1.cshtml):视图(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>

action(TestController):动作(测试控制器):

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

result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM