确定在不使用返回视图(模型)时返回哪个ASP.NET MVC视图但返回View("viewName",model)

Nat*_*ate 5 c# asp.net asp.net-mvc mobile views

我的mvc网站适用于移动和非移动浏览器; 我遇到的问题是这个.我有一些操作(为了记录原因)我不想这样做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
Run Code Online (Sandbox Code Playgroud)

这是行动

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
}
Run Code Online (Sandbox Code Playgroud)

通常我会对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
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 0

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

public enum DeliveryType
{
    Normal,
    Mobile,
    Ipad,
    MSTablet,
    AndroidTablet,
    Whatever
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在某处拥有属性或扩展方法

public DeliveryType UserDeliveryType
{
    get 
    {
        return (DeliveryType)Session["DeliveryType"];
    }
    set 
    {
        Session["UserDeliveryType"] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

您甚至可以采用不同的方法来交付视图“附加”:

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

那么你的最终决定可能是:

if (results) return View(ViewAddOn("CreateSuccess"), model);
Run Code Online (Sandbox Code Playgroud)

然后您只需确保对于每种交付类型都有相应的视图。谨慎的做法可能是构建某种检查器来验证您是否具有匹配的视图,如果没有则返回标准视图。