1

I have a List (List) of Model objects which is presented in a view. I would like to add to that list without refreshing the page - therefore i thought Ajax is a great soloution. Im currently having a hard time getting it working.

My view is rendering a PartialView which contains the list.

Can somebody give me a hint how to pass a list to the controller and then back to the view without updating the whole page?

I hope my question makes sense.

/chris

EDIT:

I've been trying with JQuery. Looks like this:

<script>
$(document).ready(function () {
    $("#btnSave").click(function () {

        $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "/Video/Index", // Controller/View
                data: { //Passing data
                    testString: $("#txtArea").val(),
                    videoID: '@(Model.Video.iVideo_ID)',
                    taskID: document.getElementById('dropVal').value
                }
            }).success(function () {
                $("#proever").load("/Video/Index");
            });
    })
})

With this method i get to HttpPost method in my controller. And i pass the parameters into it succesfully.

[HttpPost]
    public ActionResult Index(CommentViewModel viewModel)
    {
        System.Diagnostics.Debug.WriteLine(viewModel.testString);
        System.Diagnostics.Debug.WriteLine(viewModel.videoID);
        System.Diagnostics.Debug.WriteLine(viewModel.taskID);



        viewModel.testString = "new text string";

        return View(viewModel);
    }

The problem is now that i can't get the updated viewmodel back to the view.. What am i doing wrong? In this example I don't update the list but just a test string to see if i can get it updated back to the view..

8
  • Why do you want to pass the list to the controller? Commented Apr 20, 2017 at 10:30
  • I was thinking I should pass it into a [HttpPost] method in the controller but i'm not sure. I'm open to any soloutions. Commented Apr 20, 2017 at 10:31
  • You have not given enough information. Is the 'list' display only or can you edit items in the existing list? Commented Apr 20, 2017 at 10:33
  • I've added some code :) Commented Apr 20, 2017 at 10:38
  • All you method should be returning is a JsonResult indicating success of otherwise, and then you can update the DOM based on the form values (e.g. add a row to your table) - but who knows when you wont even show any relevant code) Commented Apr 20, 2017 at 10:40

3 Answers 3

1

For those who's interested I solved the problem like this:

<script>
$(document).ready(function () {
    $("#btnSave").click(function () {

        $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "/Video/AddComment", // Controller/View
                data: { //Passing data
                    //Reading text box values using Jquery
                    sComment: $("#txtArea").val(),
                    videoID: '@(Model.Video.iVideo_ID)',
                    taskID: document.getElementById('dropVal').value
                }
            }).success(function () {
                console.log("good");
                var txt = document.getElementById('txtArea').value;
                console.log(txt);

                var taskId = document.getElementById('dropVal').value;
                var taskCont = $("#dropVal option:selected").text();
                var taskContNum = Number(taskCont) - 1
                console.log(taskCont);

                var node = document.createTextNode(txt);

                var para = document.createElement("div");
                para.appendChild(node);

                document.getElementById('taskPalace').appendChild(para);

                document.getElementById('cola-' + '' + taskContNum).appendChild(para);

                document.getElementById('txtArea').value = "";
            });
    })
})

So if the request succeeds without any errors in the HttpPost method it adds the comment to the database(through the HttpPost) and the jquery adds it to the view.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to use persistent data store in your case. Currently, your async post request will change the view model data but data is lost in subsequent http requests when you try to load the view with .load(...) jquery function.

1- Send async request to http post controller action to change the data in db store for example. 2- Read the view model data from db in http get index action. ($("#proever").load("/Video/Index"))

1 Comment

I'm not sure what you mean? Perhaps you could explain it in some code?
0

You can try this:

$(document).ready(function () {
    $("#btnSave").click(function () {
    var model = {
                    testString: $("#txtArea").val(),
                    videoID: '@(Model.Video.iVideo_ID)',
                    taskID: document.getElementById('dropVal').value
                };
        $.ajax(
            {
               type: "POST", //HTTP POST Method
               url: "/Video/Index", // Controller/View                    
               data: JSON.stringify({ viewModel: model })
               async: false,
               processData: false,
               contentType: false,
               dataType: 'json'
            }).success(function (json) {
                $("#proever").html(json.responseText);
            });
    })
})

3 Comments

Thanks. I'm still having problems passing the data back to the view after it's been through the post method. Any idea how I can present the updated data?
Who in the world is up-voting this - its will throw a `500 Internal Server Error
Sorry, I made a mistake. I have updated the code. Please try now. @crellee

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.