Razor 中的部分 ViewModel、控制器

发布于 2024-11-03 01:30:35 字数 2746 浏览 1 评论 0原文

尝试使用 MVC3 + Razor 让我的工作顺利进行!

我终于理解了“视图模型”的概念来包装我的实体类并将它们定制为视图。

现在我正在组装一个页面,其中部分视图表示页面所需的不同元素(例如下拉列表、表单等),每个视图都将由一个“视图模型”表示映射到实体类并返回到我的数据库。

首先,我尝试创建一个代表组件的部分视图,该组件是数据库中元素的下拉列表,选择该组件时将呈现另一个部分视图等。

我只是无法整理为什么我无法生成此 视图下拉列表,一旦我这样做,主“控制器”如何将所有这些映射在一起?

简而言之,我很好奇 - 每个部分视图是否都需要一个控制器,即使它基于强类型模型?

分解:

我的实体模型视图包装器(从数据库获取所有可用元素

*更新* - 现在是一个工作示例,请注意,我不认为我之前问了正确的问题,但这会让您了解我想要完成的任务!下一步是将所有这些操作“移出”控制器(并将它们填充到模型默认值中)构造函数,以便以后使用)。

CharactersListViewModel.cs

Going to move avoid the 'View Model' for now until I get a little more comfortable

创建一个部分视图,显示一个下拉列表,其中角色 ID 作为值,名称作为文本,

在部分中为主页创建强类型视图、部分视图控制器:

HistoryController.cs

public class HistoryController : Controller
{
public ActionResult Index()
    {
        var list = new List<SelectListItem>();

        using (var _database = new fff_newEntities())
        {
            foreach(Character c in (from c in _database.Characters select c)){
                list.Add(new SelectListItem(){Text = c.CharacterName, Value = c.Id.ToString()});
            }
        }
        ViewBag.Clients = list;
    }
}

//
// GET: /History/Details/5

public ActionResult Details(int id)
{
    return View();
}

//
// GET: /History/Create

public ActionResult Create()
{
    return View();
} 

//
// POST: /History/Create

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        // TODO: Add insert logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

//
// GET: /History/Edit/5

public ActionResult Edit(int id)
{
    return View();
}

//
// POST: /History/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

public ActionResult Delete(int id)
{
    return View();
}

//
// POST: /History/Delete/5

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
    try
    {
        // TODO: Add delete logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

显示整个页面的索引,包括部分组件(我的下拉列表)

index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.DropDownListFor(x => x.CurrentCharacterId, (IEnumerable<SelectListItem>)ViewBag.Clients);

在这里的最后一行, @Html.Action(...) 我实际上在哪里创建下拉列表?


抱歉,如果这看起来微不足道,但我无法理解它并且我真的很想正确学习MVC3 + Razor!

Trying to get my ducks in a row with MVC3 + Razor!

I finally understand the concept of a 'View-Model' to wrap my entity classes and tailor them to a View.

Now I'm assembling a page with partial views representing different elements necessary to the page (such as drop down lists, forms, etc.) each of these will be represented by a 'View-Model' that maps to an entity class and back to my database.

First I am trying to create a partial view representing a component that is a drop-down list of elements in the database, that when selected will render another partial view, etc.

I just can't put together why I can't generate this drop-down list, and once I do how the main 'controller' maps all this together?

In short I'm curious - does each partial view need a controller even if it's based on a strongly typed model?

Breaking it down:

My Entity Model-View Wrapper (getting all the elements available from the database

*Updated* - to a working example now, note I don't think I was asking the right question before, but this will give you an idea of what I was trying to accomplish! Next step is to move all these operations 'off' the controller (and populate them in the models default constructor, for ease of use later).

CharactersListViewModel.cs

Going to move avoid the 'View Model' for now until I get a little more comfortable

Creating a partial view that displays a drop down list with the Characters' ID as a value, and name as the text, create strongly-typed view, partial view

controller for main-page in section:

HistoryController.cs

public class HistoryController : Controller
{
public ActionResult Index()
    {
        var list = new List<SelectListItem>();

        using (var _database = new fff_newEntities())
        {
            foreach(Character c in (from c in _database.Characters select c)){
                list.Add(new SelectListItem(){Text = c.CharacterName, Value = c.Id.ToString()});
            }
        }
        ViewBag.Clients = list;
    }
}

//
// GET: /History/Details/5

public ActionResult Details(int id)
{
    return View();
}

//
// GET: /History/Create

public ActionResult Create()
{
    return View();
} 

//
// POST: /History/Create

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        // TODO: Add insert logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

//
// GET: /History/Edit/5

public ActionResult Edit(int id)
{
    return View();
}

//
// POST: /History/Edit/5

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

public ActionResult Delete(int id)
{
    return View();
}

//
// POST: /History/Delete/5

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
    try
    {
        // TODO: Add delete logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

The index to display the whole page including the partial component (my drop down list)

index.cshtml:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.DropDownListFor(x => x.CurrentCharacterId, (IEnumerable<SelectListItem>)ViewBag.Clients);

On the last line here, @Html.Action(...) where do I actually create the drop-down list?


Sorry if this seems trivial but I can't wrap my head around it and I really want to learn MVC3 + Razor correctly!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肤浅与狂妄 2024-11-10 01:30:35

部分视图旨在抽象出一些 HTML/视图逻辑,以便可以在多个位置重复使用或重复(循环)。

虽然您可以有一个映射到部分的操作,并且如果相关部分进行了一些显式数据访问,这可能是可行的方法,但如果您只是从控制器本身传递它需要的所有数据,那么 - 不,您不需要控制器/操作。

由于您正在执行一些显式数据访问,我可能会为其执行一个操作...

[ChildActionOnly]
public ActionResult Characters()
{
    using (var _database = new entities())
    {
        CharactersViewModel viewModel = new CharactersViewModel();
        viewModel.Characters = _database.Characters.ToDictionary(c => c.Id, c => c.CharacterName);
        return PartialView(viewModel);
    }

}

在您看来...

@Html.Action("Characters")

当然,您执行此操作的方式没有任何问题,但我发现将其映射到操作可以使如果您想通过 ajax 请求或类似的方式从渲染的部分视图中检索 HTML,那么事情会变得更容易。

注释

  • 尝试将实体上下文对象包装在 using 中,以便它可以释放连接。
  • 您可以使用 ToDictionary 直接从查询范围中选择字典。

A partial view is meant to abstract out some HTML/View Logic so that it can be re-used either in multiple places or for repeating (looping).

Though you can have an action that maps to the partial and if the partial in question does some explicit data access this might be the way to go but if you're just passing down all the data it needs from the controller itself then - no, you don't need a Controller/Action for it.

Since you're doing some explicit data access I would probably make an action for it...

[ChildActionOnly]
public ActionResult Characters()
{
    using (var _database = new entities())
    {
        CharactersViewModel viewModel = new CharactersViewModel();
        viewModel.Characters = _database.Characters.ToDictionary(c => c.Id, c => c.CharacterName);
        return PartialView(viewModel);
    }

}

In your view...

@Html.Action("Characters")

Of course there's nothing wrong with the way you're doing it but I find having it map to an action can make things easier down the road if you ever wanted to retrieve the HTML from this rendered partial view via an ajax request or something of the sort.

Notes:

  • Try to wrap your entity context object in a using so it can dispose of the connection.
  • You can use ToDictionary to select your dictionary directly from the query scope.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文