1

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 ?

June
  • 43
  • 6
  • 1
    You can get updated data from an json API that your backend provides. You can call it with JQuery Ajax request, where you POST your data to the backend and return relevant data based on it. Look here e.g. https://stackoverflow.com/q/59325946/6568785 Also, you should probably not hardcode the initial model inside the click event, but rather have the ajax request there. – Hyperdingo Dec 04 '20 at 17:17

1 Answers1

1

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: enter image description here 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: enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22