Home How return JSON endpoint or a partial view in same function?
Reply: 0

How return JSON endpoint or a partial view in same function?

WebDevGuy2 Published in 2017-09-13 20:57:12Z

Working on MVC5 app. I have a search form. The client wants me to either show the search results on the page, or "expose necessary actions as JSON endpoints".

The partial view search works fine. But, I can't get the JSON part of the code to return in a way that it can be "consumed". (If I understand the requirement.) Any ideas how I can do this (within the same function)?

Here's a snippet of code....

   public ActionResult _SearchIt(SearchViewModel response)
       : // I do all the work of getting the data based on the users inputs
       // now this is where I either return the partial view or JSON endpoint...

            if (response.ReturnJson == true)
                // return a serialized JSON object rather than the partial view
                string json = JsonConvert.SerializeObject(model);
                return this.Content(json);   // this returns the data properly, 
                                             // but not in a consumable manner
                // this works perfect
                return this.PartialView(model);

I am calling this from an AJAX form... options are...

   ViewBag.Title = "Index";
   var options = new AjaxOptions { UpdateTargetId = "searchResultRows", 
          InsertionMode = InsertionMode.Replace, LoadingElementId = "divLoading" };

Then, the AJAX form, using those options....

<div class="container">
    @using (Ajax.BeginForm("_SearchFlight", options))
        <div class="row">
              (All the search form controls)

The problem is, the UpdateTargetId always kicks in and I see the action result on the page (either the partial or the JSON result), even if I just want JSON returned.

Any ideas/suggestions? Thanks!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.349102 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO