c# - 从视图中切换 DataContext
问题描述
我正在开发一个使用 2 个不同数据存储的 ASP.NET MVC 应用程序。我为每个连接创建了 2 个不同的上下文类。我已经单独发短信了,两者都工作得很好
背景一:
public class DbContextA : DbContext
{
public DbContextA ()
: base("name=DbContextA ")
{
}
public virtual DbSet<Producto> Productos { get; set; }
}
上下文 2:
public class DbContextB : DbContext
{
public DbContextB ()
: base("name=DbContextB ")
{
}
public virtual DbSet<Producto> Productos { get; set; }
}
现在我想从视图中切换两个上下文。为此,我在视图中创建了一个 DropDownList:
@using (Html.BeginForm())
{
<p>Please select the data storage mode:</p>
<div>
<select id="StorageTypes" name="StorageTypes">
<option value="1">Storage 1</option>
<option value="2">Storage 2</option>
</select>
<input type="submit" value="Accept" />
</div>
}
但我不知道如何让 ir 像我预期的那样工作,我从控制器尝试如下:
private DbContextA db1 = new DbContextA();
private DbContextB db2 = new DbContextB();
private string selStorageValue;
// GET: Home
public ActionResult Index()
{
if(ViewData["Context"] != null)
{
if (ViewData["Context"].ToString() == "1")
{
var context = db1;
return View(context.Productos.ToList());
}
else if (ViewData["Context"].ToString() == "2")
{
var context = db2;
return View(context.Productos.ToList());
}
else
{
var context = db1;
return View(context.Productos.ToList());
}
} else
{
var context = db1;
return View(context.Productos.ToList());
}
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
selStorageValue = form["StorageTypes"].ToString();
ViewData["Context"] = selStorageValue;
return View("Index");
}
但我不知道怎么做。我会感谢任何帮助!
解决方案
[HttpPost]
public ActionResult Index(FormCollection form)
{
private DbContextA db1 = new DbContextA();
private DbContextB db2 = new DbContextB();
string selStorageValue = form["StorageTypes"];
// Assuming selStorageValue has some value.
ViewBag.Productos = null;
if (selStorageValue != null)
{
if(selStorageValue.ToString()=="1"){
ViewBag.Productos=db1.Productos.ToList();
}
else if(selStorageValue.ToString()=="2"){
ViewBag.Productos=db2.Productos.ToList();
}
}
else{
ViewBag.Productos=db1.Productos.ToList();
}
return View(); //View must be binded
}
看法
@{
ViewBag.Title = "Title";
Layout = " layout File address";
List<Producto> ProductoList = (List<Producto>)ViewBag.Productos;
}
现在您在视图中看到了 Productos 列表,现在使用您希望在视图中实现它的方式。例如创建一个选择框
<div id="someId">
@Html.DropDownList("Productos",
new SelectList
(
ProductoList, "ProductoId", "ProductoName"
),
new { @class = "form-control" })
</div>
推荐阅读
- python - mplcursors 仅显示 y 坐标
- javascript - Nuxt js custum js文件未加载
- python - Python - 在具有容错性的列表中测量某个值的最长子序列
- c# - Windbg 从 .foreach 值解析变量
- c++ - 我收到以下错误:在抛出 'std::bad_alloc' 的实例后调用终止
- python - /personal_detail/ 处的 IntegrityError
- reactjs - 自定义反应表
“全选”复选框列位置和样式 - swift - 在 Swift 中,如何在嵌套计时器中引用“self”?
- r - 以公里为单位对具有给定分辨率的矢量进行栅格化
- c++ - 如何在 C++ 中更改我的连接图,以便每个顶点都可以容纳一个对象?