3

I am considering building a SPA using AJAX.BeginForm, however I am facing an issue when a user has JavaScript disabled, instead of redirecting him to _Layout.cshtml + PartialView.cshtml, it redirects him to just the PartialView.cshtml..

Is there a way to include the Layout and the PartialView in it (where it would be if JavaScript was enabled)?

Thanks

Edit:

Awesome.. Thanks.. I managed to get it working but I am not sure it's the best implementation..

    [HttpPost]
    public ActionResult Index(Newsletter newsletter)
    {
        if (ModelState.IsValid)
        {
            db.Newsletters.Add(newsletter);
            db.SaveChanges();
            ViewData["message"] = "thanks for signing up to our newsletter!";
            if (Request.IsAjaxRequest())
            {
                return PartialView( "SimpleMessage" );
            }
        }
        return View();
    }

And SimpleMessage.phtml is simply just @ViewData["message"];

whereas my View.phtml I have got a condition and checks whether ViewBag["message"] is set or not. If it's set, then it means it's a postback and doesn't show the form and shows the message instead, or else it shows the form:

4

1 回答 1

5

您可以检查是否通过 Ajax 调用了 Action,并返回不同类型的结果

public ActionResult MyAction()
{
    if(Request.IsAjaxRequest()) {
        // Html fragment
        return PartialView();
    }
    else {
        // Complete HTML page
        return View();
    }
}

如果是回发,您也可以传递您的模型或简单类型(int、string):

[HttpPost]
public ActionResult MyAction(Model model)
{
    if(Request.IsAjaxRequest()) {
        // Html fragment
        return PartialView(model);
    }
    else {
        // Complete HTML page
        return View(model);
    }
}

编辑:在你的具体情况下,我会这样做,但这只是我的偏好。

[HttpPost]
public ActionResult Index(Newsletter newsletter)
{
    if (ModelState.IsValid)
    {
        db.Newsletters.Add(newsletter);
        db.SaveChanges();
        if (Request.IsAjaxRequest())
            return PartialView("SimpleMessage");
        else
            return View("SimpleMessage")
    }
    if (Request.IsAjaxRequest())
        return PartialView(newsletter);
    else
        return View(newsletter);
}
于 2013-03-13T18:33:32.003 回答