开发者

Asp.Net Mvc - Switch from Server to Ajax

开发者 https://www.devze.com 2022-12-19 10:23 出处:网络
Is there a clean way to manage my Asp.Net Mvc Web site to both work corre开发者_Go百科ctly if javascript is enabled/disabled. Because, for now, I have to do hack like that to make both work. I think t

Is there a clean way to manage my Asp.Net Mvc Web site to both work corre开发者_Go百科ctly if javascript is enabled/disabled. Because, for now, I have to do hack like that to make both work. I think that doesn't make code that is easy maintainable and reusable...

if (Request.IsAjaxRequest()) 
{                        
    return PartialView("SignUpForm", user);
}
else 
{
    return View("SignUp", user);
}


In this answer I've outlined a modal window technique that works cleanly without javascript; no code changes if you wanted to disable all the modal and javascript functionality.

Simple ASP.NET MVC CRUD views opening/closing in JavaScript UI dialog

The bits that I think are most important for you is custom ViewEngine:

public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
    //you might have to customize this bit
    if (controllerContext.HttpContext.Request.IsAjaxRequest())
        return base.FindView(controllerContext, viewName, "Modal", useCache);

    return base.FindView(controllerContext, viewName, "Site", useCache);
}

This code turns off the javascript and the surrounding template by loading a separate MasterPage if a request is from ajax or not. By switching the masterpage inside your own custom ViewEngine you avoid the if( Ajax ) code in all of your controllers and keeps thing clean.

0

精彩评论

暂无评论...
验证码 换一张
取 消