当不使用return View(model)而是使用return View("viewName", model)时,确定返回哪个ASP.NET MVC视图。

5

我已经将我的mvc站点成功地应用于移动和非移动浏览器中;但是我遇到的问题是,我有一些Actions(出于日志记录的原因)我不想执行return RedirectToAction(...);,所以我一直在使用return View("OtherView", model);,这个方法在非移动设备上可行,在移动设备上就会出现找不到OtherView.Mobile.cshtml的情况。有什么办法能够解决这个问题吗?

这些是视图。

Views/Account/Create.cshtml
Views/Account/Create.Mobile.cshtml
Views/Account/CreateSuccess.cshtml
Views/Account/CreateSuccess.Mobile.cshtml

这是操作。
public ActionResult Create(FormCollection form)
{
    TryUpdateModel(model);

    if(!ModelState.IsValid) { return View(); }  // this works correctly

    var model = new Account();

    var results = database.CreateAccount(model);

    if(results) return View("CreateSuccess", model); // trying to make this dynamic

    return View(model); // this works correctly
}

通常情况下,我只需执行return RedirectToAction(...);即可转到帐户详细页面,但这将生成额外的日志记录(用于读取此用户)以及详细页面无法访问密码。由于ActionResult Create最初具有密码,因此它可以向用户显示密码以供确认,然后再次不可见。
明确一点,我不想执行if (Request.Browser.IsMobileDevice) mobile else full,因为我可能会为iPad或其他设备添加另一组移动视图。
Views/Account/Create.cshtml
Views/Account/Create.Mobile.cshtml
Views/Account/Create.iPad.cshtml
Views/Account/CreateSuccess.cshtml
Views/Account/CreateSuccess.Mobile.cshtml
Views/Account/CreateSuccess.iPad.cshtml
2个回答

0

我会在第一次使用时设置一个会话变量,用于标识所有支持的视图的“交付类型”。

public enum DeliveryType
{
    Normal,
    Mobile,
    Ipad,
    MSTablet,
    AndroidTablet,
    Whatever
}

然后你可以在某个地方拥有一个属性或扩展方法。
public DeliveryType UserDeliveryType
{
    get 
    {
        return (DeliveryType)Session["DeliveryType"];
    }
    set 
    {
        Session["UserDeliveryType"] = value;
    }
}

你甚至可以使用不同的方法来传递“add on”视图:

public string ViewAddOn(string viewName)
{
    return (UserDeliveryType != DeliveryType.Normal) ?
        string.Format("{0}.{1}", viewName, UserDeliveryType.ToString()) :
        viewName;
}

那么你的最终调用可能是:

if (results) return View(ViewAddOn("CreateSuccess"), model);

然后你只需要确保每种交付类型都有相应的视图。建议构建某种检查器来验证是否有匹配的视图,如果没有,则返回标准视图。


0

您可以创建一个带有 ViewData 变量的 Partial 的伪视图。@Html.Partial 将找到正确的视图。

类似这样:

CustomView.cshtml:
if (ViewData.ContainsKey("PartialViewName")) {
@Html.Partial(ViewData[PartialViewName]);
}

Controller.cs:
public ActionResult Create(FormCollection form)
{
    TryUpdateModel(model);
    ViewData[PartialViewName] = "CreateSuccess";
    if(!ModelState.IsValid) { return View(); }  // this works correctly

    var model = new Account();

    var results = database.CreateAccount(model);

    if(results) return View("CustomView", model); // trying to make this dynamic

    return View(model); // this works correctly
}

你现在可以有 CreateSuccess.cshtml 和 CreateSuccess.Mobile.cshtml。

注意:你的所有应用程序中只需要一个 CustomeView.cshtml。

注意2:你始终可以以其他方式传递参数,例如 viewbag 或任何让您感觉更舒适的技术:D

这更像是一种 hack 而不是解决方案。如果您想到了更漂亮的东西,请告诉我们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接