gpt4 book ai didi

c# - 确定在不使用 return View(model) 但返回 View ("viewName", model 时返回哪个 ASP.NET MVC View

转载 作者:太空狗 更新时间:2023-10-29 23:51:58 25 4
gpt4 key购买 nike

我的 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

这是行动

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 或其他设备添加另一组移动 View :

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

最佳答案

我会在他们第一次使用时设置一个 session 变量,这将是一个标识所有支持的 View 的“交付类型”。

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

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

public DeliveryType UserDeliveryType
{
get
{
return (DeliveryType)Session["DeliveryType"];
}
set
{
Session["UserDeliveryType"] = value;
}
}

您甚至可以使用不同的方法来交付 View “附加”:

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

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

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

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

关于c# - 确定在不使用 return View(model) 但返回 View ("viewName", model 时返回哪个 ASP.NET MVC View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13711874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com