简体   繁体   中英

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

I'm using asp.net core and MVC architecture. I have a jquery event handler on a button click. If the user click the button, I apply different change to the DOM, based on data I fetch from my c# model. The data I need from my model change depending on user input. 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.

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

You can use form post or ajax:

1.form post(submit the form to action,and action return a view with the data you want):

view(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):

view(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: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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