1

I have ajax that return partial view with strongly type I want in the success to get the values of the model. is it possible? the code return:

return View("Test", Model);

in the ajax: I want to get the model in the data varible

 success: function (data) {
       data.
           }
rikush
  • 520
  • 1
  • 6
  • 20
  • Take a look at http://stackoverflow.com/questions/18050894/how-to-call-an-actionresult-from-jquery and http://stackoverflow.com/questions/33201617/using-jquery-ajax-to-call-actionresult-method-in-controller-and-return-data as they both address your question. – jonesy Mar 13 '17 at 13:04

3 Answers3

0

Your Partial View would need to return JSON data for you to be able to access the data like that.

In your controller (I'm assuming this is a HTTPPost call):

return Json(new { id = 1, name = "Test" });

In your JS Ajax call:

success: function(data) {
    alert(data.name); //alerts 'Test'
}

update OK, if you want to have the Partial View returned and the model, you could return the View as you already are then convert the model to a JSON string to be accessed and used in JS in the View maybe? Here's a rough example...

so in Controller:

using System.Web.Script.Serialization;
...
var jsonstring = new JavaScriptSerializer().Serialize(Model); 
...
ViewBag.JsonString = jsonString;

then in the Partial View:

@{
   var jsonString = ViewBag.JsonString;
}
<script>
var data = JSON.parse("@jsonString");
alert(data.name); //alerts 'Test'
</script>
scgough
  • 5,099
  • 3
  • 30
  • 48
  • hi, thank you but I need to return the partial view and the model, in your example how do I use in the partirl view? – rikush Mar 13 '17 at 13:59
  • do you have `@{ var jsonString = ViewBag.JsonString; }` at the top of your Partial View (before the ` – scgough Mar 13 '17 at 14:22
  • i did it, but I get the error because the script is in the main view , and it doesnt know the partial, do you have any idea? – rikush Mar 13 '17 at 14:26
  • you'll need to put that script in the partial and execute JS from there. – scgough Mar 13 '17 at 14:27
0

No, for that you need to return JsonResult back from controller action which would be like:

return Json(new {response =  Model });

Now it ajax success, you can access the result from json object which is returned :

success: function (data) {
       console.log(data);
           }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Try this is Ajax form

OnSuccess = "ShowMessage()"

and script is

    <script>
    function ShowMessage() {
                document.getElementById('info').value='YOUR_MESSAGE';
                setTimeout(function () {
                $("#info").hide();
                }, 3000);
            }
    <script>

and Your Html tag should be like this

<div id="info"></div>
Supraj V
  • 967
  • 1
  • 10
  • 19