Palindromer
Palindromer

Reputation: 994

Good practice when ajax and static page use same partialView?

When user comes on my site by url, controller generates _Layout + partialView inside.

Then when user walks by site, controller generates same partialView and sends by ajax.

Is there a good solution for this case?

P.S.: My workaround:

public class HomeController : Controller
{
    public ActionResult Index(int id, bool ajax = false)
    {
        var model = GetModelById(id);

        return ajax ? (ActionResult) PartialView(model) : View(model);
    }
}

Where /Home/Index/42 - for static page and /Home/Index/42?ajax=true - for ajax.

Upvotes: 0

Views: 38

Answers (1)

Palindromer
Palindromer

Reputation: 994

To identify ajax request:

var isAjax = Request.IsAjaxRequest()

Or alternative in Asp.Net Core:

var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";

Upvotes: 1

Related Questions