【问题标题】:Pass specific model from one view to partial view?将特定模型从一个视图传递到部分视图?
【发布时间】:2014-02-03 14:44:51
【问题描述】:

我有一个带有模型的强类型视图,它表示列表中的多个对象。在这个视图中,我生成 Grid,每个对象代表网格中的一行。然后我将此模型列表中的特定对象传递给局部视图。这个局部视图实际上是一个弹出窗口。在弹出窗口中,我有一个表单,用户可以在其中更正一行(一个对象)并提交回 Action,我将更改保存到数据库。当我单击特定的“行”时,如何将特定对象从视图传递到部分视图?

是否可以将特定行的 ID 例如保存到隐藏字段,然后在渲染局部视图或将模型传递给局部视图时从隐藏字段动态读取此值?还是整个概念错了?

查看代码

@model IEnumerable<Loyalty.Models.GridColumns>
@using GridMvc.Html
@using GridMvc.Sorting

<input type="button" id="opener" title="open popup" value="test1"/>
<a onclick="EditUser(1)">edit</a>

@Html.Grid(Model).AutoGenerateColumns()

<div id="EditUser" title="Popravi uporbnika">
    @{
        //Here I would like to get value from hidden field and change it with value 1
        //in a WHERE sentance in the line below
        Html.RenderPartial("EditUser", Model.Where(m => m.ID == 1).Single());
    }
</div>

<script  type="text/javascript">
    $("#opener").click(function () {
        $("#EditUser").dialog("open");
    });
    $(function() {
        $("#EditUser").dialog({
            open: function() {
                $("body").addClass("blur");
            },
            clse: function () {
                $("body").removeClass("blur");
            },
            modal: true,
            closeText:  "Close",
            autoOpen: false,
            width: 800,
            height: 600
        });
    });

    }
</script>

部分查看代码

@model Loyalty.Models.GridColumns

@using (Ajax.BeginForm("UpdateUser", "Home", new AjaxOptions () { UpdateTargetId="ID", OnSuccess="onSuccess()"}))
    {
        <fieldset class="PopUp">
            <legend class="PopUp">General data</legend>
            <div class="EditLabel">
                Name:
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.FirstName)
            </div>

            <div class="EditLabel">
                Last name:
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.LastName)
            </div>

             <div class="EditLabel">
                Birth date: 
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.BirthDate, "{0:dd-MMM-yyyy}")
            </div>

            <div class="EditLabel">
                Gender: 
            </div>
            <div class="EditValue">
                @{
                    var item1 = new SelectListItem();
                    item1.Text = "male";
                    var item2 = new SelectListItem();
                    item2.Text = "female";
                    List<SelectListItem> items = new List<SelectListItem>();
                    items.Add(item1);
                    items.Add(item2);
                    var SelectItems = new SelectList(items, "Value", "Text");
                }

                @Html.DropDownListFor(m => m.Gender, SelectItems)
            </div>
        </fieldset>

        <fieldset class="PopUp">
            <legend class="PopUp">Address</legend>
            <div class="EditLabel">
                Street:
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.Street)
            </div>

            <div class="EditLabel">
                House no.:
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.HouseNumber)
            </div>

            <div class="EditLabel">
                Town:
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.Town)
            </div>

            <div class="EditLabel">
                Post code:
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.PostNumber)
            </div>
        </fieldset>

        <fieldset class="PopUp">
            <legend class="PopUp">Contact info</legend>
            <div class="EditLabel">
                Phone: 
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.PhoneNumber)
            </div>

            <div class="EditLabel">
                E-mail: 
            </div>
            <div class="EditValue">
                @Html.TextBoxFor(m => m.Email)
            </div>
        </fieldset>
    }

主视图操作

    public ActionResult Index()
            {    
                var UsersCollection = new List<GridColumns>();
                for (int i = 1; i <= 31; i++)
                {
                    bool disc = false;
                    if (i % 2 == 0)
                    {
                        disc = true;
                    }
                    else
                    {
                        disc = false;
                    }

                    UsersCollection.Add(new GridColumns() {ID = i, BirthDate = new DateTime(2014,1,i), Email = "user" + i + "@email.com", FirstName = "User1" + i, LastName = "User1LastName" + i, Gender = "male", Discount = disc, Cupons = i });
                }

                return View(UsersCollection);
            }

部分视图操作

    [HttpPost]
    public ActionResult UpdateUser(GridColumns person)
    {
        return PartialView();
    }

Partial View action is called when submitting popup form.

型号

[GridTable(PagingEnabled=true, PageSize=20)]
    public class GridColumns
    {
        [GridColumn(Title="ID", SortEnabled=true)]
        public int ID { get; set; }

        [GridColumn(Title="First name", FilterEnabled=true, SortEnabled=true)]
        public string FirstName { get; set; }

        [GridColumn(Title = "Last name", FilterEnabled = true, SortEnabled = true)]
        public string LastName { get; set; }

        [GridColumn(Title = "Birth date", FilterEnabled = true, Width = "150", Format = "{0:dd-MMM-yyyy}")]
        public DateTime BirthDate { get; set; }

        [GridColumn(Title = "gender", FilterEnabled = true)]
        public string Gender { get; set; }

        [GridColumn(Title = "e-mail", FilterEnabled = true, SortEnabled = true)]
        public string Email { get; set; }

        [GridColumn(Title = "Phone", FilterEnabled = true, SortEnabled = true)]
        public string PhoneNumber { get; set; }

        [GridColumn(Title = "Street", FilterEnabled = true)]
        public string Street { get; set; }

        [GridColumn(Title = "House no.", FilterEnabled = true)]
        public string HouseNumber { get; set; }

        [GridColumn(Title = "Town", FilterEnabled = true)]
        public string Town { get; set; }

        [GridColumn(Title = "Post number", FilterEnabled = true)]
        public int PostNumber { get; set; }            
    }

【问题讨论】:

  • GridColumns 是否包含您所追求的 Id 作为属性?
  • 是的。该代码有效,但我想去掉这部分代码Html.RenderPartial("EditUser", Model.Where(m =&gt; m.ID == 1).Single()); 中的值 1 并将其替换为隐藏字段中的值。

标签: c# asp.net-mvc model partial-views


【解决方案1】:

我并不是说要苛刻,但是如果您要为 Web 开发,那么您需要了解 Web 的工作原理。在 HTTP 中,您有一个服务器和一个客户端。客户端向服务器发送 request 以获取某些资源,而服务器发送回 response。这称为请求-响应周期。 “循环”部分是关键,因为连接不会无限期地保持。服务器发送响应后,连接关闭,如果客户端需要进一步的东西,它会发出一个新的请求。

所以,现在让我们考虑一下您要完成的工作。您有一个在 服务器端 呈现的局部视图,并且您希望根据将要发生的事情 客户端(单击)呈现不同的东西。那是不可能的。当用户可以点击某些东西时,服务器已经完成了它的工作并继续前进。

现在,正是由于这个限制,才开发了 AJAX。 AJAX 只是一种在页面上发出 HTTP 请求而无需强制重新加载浏览器的方法。将其视为网页中的迷你精简浏览器。如果您希望基于用户点击呈现一些 HTML,那么您必须使用 JavaScript 来捕获并处理该点击事件,向服务器发送 HTTP 请求以获取该位 HTML,然后将返回的数据呈现到页面一次您收到回复。简单来说,这可以通过以下方式实现:

JavaScript

$('.row').on('click', function () {
    $.get('/url/to/action/that/returns/html', { id = [something] }, function (result) {
        $('#Something').html(result);
    }
});

控制器动作

public ActionResult GetRowHtml(int id)
{
   // whatever
   return View("_RowHtml");
}

局部视图

@{ Layout = null; }
<!-- your html -->

由于我无法为您做出这些假设,您必须填写的部分是:

  1. 如何在 JS 中获取行 ID。 您可以将其作为数据属性添加到表格行中,然后使用 $(this).data('id') 检索它。您可以简单地使用$(this).find('td.myIdCell').text() 从已知数据单元中提取它。您不能真正将其设置为行的实际 id 属性,因为 HTML id 必须以字母字符开头,但您可能会执行类似 id="row1" 的操作,其中 1 是 id 并使用 JS 字符串操作函数或正则表达式模式将其拉出。

  2. id 将实际用于您的操作。这只是您的直接业务逻辑。

  3. 返回的 HTML 会发生什么。我只是简单地设置了一些带有 id 的元素的 HTML 内容,#Something。您的逻辑可能会更复杂,可能需要先选择表或其他内容,然后再将项目附加到 DOM。

【讨论】:

  • 非常感谢您的回答!当你把它放在网络如何运作的环境中时,它是有道理的。
【解决方案2】:

我会将一个 javascript 函数绑定到网格的行单击事件,并假设网格的键是您所追求的 ID:

function showPopup(id){
     var url = 'someActionThatPopulatesPartialView/' + id;
     $.get(url, function(data){
          $('#EditUser').html(data);
     });
}

【讨论】:

  • Actions 会是什么样子?现在它们看起来像这样(我在上面编辑了我的问题以查看它们现在的样子)。如果我在 UpdateUser 操作中只接受行的 ID,那么我必须将该特定对象返回到部分视图,但是我必须先从数据库中获取它?
  • 我对您的应用程序了解得不够多,无法告诉您。
  • 我们添加了有问题的模型代码。也许它也会向其他人澄清一些事情。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
相关资源
最近更新 更多