简体   繁体   English

如何从另一个视图模型检索一个视图模型?

[英]How do I retrieve a viewmodel from another viewmodel?

I have this ViewModel which incorporates 3 other viewmodels and a list: 我有这个ViewModel ,其中包含3个其他viewmodel和一个列表:

public class GroupPageViewModel{
    public string GroupName { get; set; }
    public GroupSelectViewModel _groupSelectVM {get; set;}
    public List<User> _users { get; set; }
    public ViewModelStudent _studentVM { get; set; }
    public ViewModelGroupMembers _groupMembersVM { get; set; }
}

In the view I can access each of these sub-ViewModels by Model._groupSelectVM , each of the sub-ViewModels are associated with a partial view. 在视图中,我可以通过Model._groupSelectVM访问这些sub-ViewModels的每一个,每个sub-ViewModels与局部视图相关联。 The problem arises when I need to refresh just one or two partial views, I'm not sure how to access the inner ViewModels returned in an Ajax success, and as I'm relatively new to MVC and asp.net in general. 当我只需要刷新一个或两个局部视图时,就会出现问题,我不确定如何访问Ajax成功返回的内部ViewModel,并且由于我对MVC和asp.net相对较新。 And I literally know next to nothing about JavaScript, jquery or Ajax. 而且我几乎不了解JavaScript,jquery或Ajax。

How would I go about getting a specific ViewModel from the main ViewModel in an Ajax success? 在Ajax成功的情况下,我将如何从主ViewModel获取特定的ViewModel

This is just one example for the clarification requested all the others are pretty much the same (although some of them might need to update mutliple partial views - 这只是说明的一个示例,所有其他示例几乎都是相同的(尽管其中一些可能需要更新多个局部视图-

From the controller: 从控制器:

[HttpPost]
public ActionResult Index(string groupChoice = "0", string newGroup = "")
    {
        string groupName = "";

        if (groupChoice == "0" && newGroup != "")
        {
            if (ModelState.IsValid)
            {
                Group group = new Group
                {
                    GroupName = newGroup,
                    Active = true
                };

                db.Groups.Add(group);
                db.SaveChanges();
                PopulateLists();
            }
        }
        else if (groupList == null)
        {
            groupList = (List<SelectListItem>)Session["groupList"];                
            Session["groupName"] = groupName = groupList.Where(m => m.Value == groupChoice).FirstOrDefault().Text;
            MembersInSpecificGroup(groupName, groupMembers, groupMembersList);
            groupPageVM._groupMembersVM = groupMembers;
        }

        return View("GroupSelection", groupPageVM);
    }

The script: 剧本:

$(document).ready(function () {
        $('#selectedGroup').change(function () {
            var data = {
                groupChoice: $('#selectedGroup').val()
            };

            var groupChoice = $('#selectedGroup').val();
            $.ajax({
                url: '/Group/Index/',
                type: 'POST',
                data: { groupChoice: groupChoice },
                success: function (data) {
                    setTimeout(function () {
                        delayGroupSuccess(data);
                    }, delay);

                }
            });
        })
    });
    function delayGroupSuccess(data) {
        $("#groupSelect").html(data);
    }

The main page: 主页:

 @model EMBAProgram.ViewModels.GroupPageViewModel @{ Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Group Selection</h2> <div class="row" id="groupSelect"> @{ Html.RenderPartial("_GroupSelect", Model._groupSelectVM);} </div> <hr size="5" /> <div style="display: flex;"> <div> @{Html.RenderPartial("_Students", Model._studentVM);} </div> <div> @{ Html.RenderPartial("_GroupMembers", Model._groupMembersVM);} </div> <div> @{ Html.RenderPartial("_Users", Model._users);} </div> <br style="clear: left;" /> </div> 

The partial view: 部分视图:

 @model EMBAProgram.ViewModels.ViewModelGroupMembers <div class="table-responsive" id="groupResults"> <table class="table table-condensed table-responsive"> <thead> <tr> <th>@Html.DisplayName("M-Number")</th> <th>@Html.DisplayName("Name")</th> <th>@Html.DisplayName("Student")</th> </tr> </thead> <tbody> @foreach (var item in Model._groupVM) { <tr> <td>@Html.DisplayFor(m => item.MNumber)</td> <td>@Html.DisplayFor(m => item.Name)</td> <td>@Html.DisplayFor(m => item.Student)</td> </tr> } </tbody> </table> </div> 

Basically I need to be able pull the ViewModel for the partial view from the main ViewModel (which I believe is what is being returned in the Ajax,) and refresh the partial view. 基本上,我需要能够拉动ViewModel从主局部视图ViewModel (我相信是什么是在阿贾克斯,返回),并刷新局部视图。

I removed the original answer, it's available in the edit log if folks want to see it I think. 我删除了原始答案,如果人们想看到我认为的答案,则可在编辑日志中找到该答案。 But it was taking up too much space and was incorrect. 但是它占用了太多空间并且是错误的。


You can return multiple partial views, I thought it was a built in way to get them to a string (I was in a rush in my comment), but I've got a working example. 您可以返回多个局部视图,我认为这是将它们转换为字符串的一种内置方式(我急于发表评论),但是我有一个有效的示例。

In the controller I have the following: 在控制器中,我有以下内容:

public ActionResult Index()
{
    var model = new TestViewModel
    {
        Students = GetStudents(),
        Categories = GetCategories(),
        Groups = GetGroups()
    };

    return View("Index", model);
}

// Returns multiple partial views as strings.
public ActionResult StudentsAndGroups()
{
    return Json(new
    {
        Students = RenderRazorViewToString("_Students", GetStudents()),
        Groups = RenderRazorViewToString("_Groups", GetGroups())
    }, JsonRequestBehavior.AllowGet);
}

// Creates a string from a Partial View render.
private string RenderRazorViewToString(string viewName, object model)
{

    ControllerContext.Controller.ViewData.Model = model;

    using (var stringWriter = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData, stringWriter);
        viewResult.View.Render(viewContext, stringWriter);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return stringWriter.GetStringBuilder().ToString();
    }
}

I have my main index view that looks like the following: 我的主索引视图如下所示:

<button class="refresh">Refresh</button>

<div class="row">
    <div class="col-md-4 students">
        @{
            Html.RenderPartial("_Students", Model.Students);
        }
    </div>

    <div class="col-md-4">
        @{
            Html.RenderPartial("_Category", Model.Categories);
        }
    </div>

    <div class="col-md-4 groups">
        @{
            Html.RenderPartial("_Groups", Model.Groups);
        }
    </div>
</div>

@section scripts
{
    <script type="text/javascript">
        $(".refresh").click(function () {
            $.get("/Home/StudentsAndGroups", function (d) {
                $(".students").html(d.Students);
                $(".groups").html(d.Groups);
            })
        });
    </script>
}

The controller action StudentsAndGroups turns two partial views into strings. 控制器动作StudentsAndGroups将两个局部视图转换为字符串。 From there, the javascript calls that view and accesses the elements and returns them. 从那里,javascript调用查看和访问元素并返回它们。

Helper method for rendering a view as a string was found here: https://stackoverflow.com/a/34968687/6509508 在此处找到了将视图呈现为字符串的帮助方法: https : //stackoverflow.com/a/34968687/6509508

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将observable从一个命名空间viewModel更新到另一个 - How do I update an observable from one namespaced viewModel to another 如何将数据从一个viewModel传递到另一个ViewModel Knockout JS - How to carry the data from one viewModel to another ViewModel Knockout JS 如何将项目从ko.mapping.fromJS数组复制到viewmodel的另一个属性? - How do I copy an item from a ko.mapping.fromJS Array to another property of the viewmodel? 如何从视图调用我的 viewmodel 函数 - viewmodel 的子级(knockout.js) - How do I call my viewmodel function from its view - child of viewmodel (knockout.js) 如何在bindingHandler中从ViewModel调用函数 - How Do I Call A Function from ViewModel inside bindingHandler 如何从同一viewModel中的不同分支访问后代? - How do I access descendants from a different branch in the same viewModel? 如何从另一个视图模型计算一个knockout observableArray? - How to compute a knockout observableArray from another viewmodel? 如何在不相关的ViewModel中设置数据 - How do I set data in an unrelated ViewModel 如何从父视图模型访问孙子视图模型? - How to access grandchild viewmodel from parent viewmodel? 如何从Ajax调用中从一个控制器检索视图模型数据 - How to retrieve viewmodel data from one controller out of an ajax call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM