【问题标题】:MVC2: Is rendering List<object> possible in Create context?MVC2:在创建上下文中可以渲染 List<object> 吗?
【发布时间】:2011-11-21 10:09:02
【问题描述】:

我有这个模型:

public class Package
{
    public string CustomerName { get; set; }
    public List<Product> Products { get; set; }
}

public class Product
{
    public int Quantity { get; set; }
    public string Name { get; set; }
}

当我添加 Create 的视图时,代码是:

    <fieldset>
        <legend>Fields</legend>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.CustomerName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.CustomerName) %>
            <%: Html.ValidationMessageFor(model => model.CustomerName) %>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

如何管理产品列表? 我可以获得按钮或其他东西来创建新产品并将其添加到 Products 列表中吗?

谢谢

【问题讨论】:

  • 另外,查看 MvcScaffolding,它将生成您所有的控制器、模型和视图。相当灵活,mvcscaffolding.codeplex.com.

标签: asp.net asp.net-mvc asp.net-mvc-2


【解决方案1】:

对于创建按钮,您也可以使用 HTML.ActionLink() 或 Ajax.ActionLink() 定义为按钮,例如:

<% Response.Write(Html.ActionLink("Add Product", "Create", new { id = tId, tNum = tNum }, new { @class = "oldVal" })); %>

它会在你的页面上创建一个按钮,在这里你可以看到不同的属性(所以只要检查一下你会发现它很有用)......并且从这两者中使用哪个更多取决于你想要的行动...

在你的控制器中:

public ActionResult Create() 
{
    // do same as mentioned by [gnome][1]
}

这里是示例:模态弹出窗口,声明为页面的部分视图 [使用 Ajax.ActionLink() 的部分视图]

using (Ajax.BeginForm("Login", "Users", null, new AjaxOptions() { UpdateTargetId = "divLoginPopupContent" }))
            {
                Response.Write(Html.ValidationSummary(true));
    %>
                <ul class="chooseQuestion">
                    <li>
                        <div class="short">
                            <%= Html.LabelFor(model => model.LoginEmail)%>
                        </div>
                        <div class="editor-field">
                            <%= Html.TextBoxFor(model => model.LoginEmail)%>
                            <%= Html.ValidationMessageFor(model => model.LoginEmail)%>
                        </div>
                    </li><li>
                        <div class="short">
                            <%= Html.LabelFor(model => model.LoginPassword)%>
                        </div>
                        <div class="editor-field">
                            <%= Html.PasswordFor(model => model.LoginPassword)%>
                            <%= Html.ValidationMessageFor(model => model.LoginPassword)%>
                        </div>
                    </li><li>
                        <div class="checkbox">                
                            <%= Html.CheckBoxFor(model => model.Remember)%>
                            <%= Html.LabelFor(model => model.Remember)%>
                        </div>
                    </li><li>
                        <input type="submit" class="button" value="Login" id="btnLoginSubmit" />
                        <div id="divlogin_ajaxloading" style="display:none; vertical-align:top; text-align:center;"><img alt="" src="/images/ajax-loader.gif" /></div>
                    </li>
                </ul> 
            }

您的局部视图操作:

public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.LoginEmail, model.LoginPassword))
                {
                    return Redirect("/MyPage");
                }
                else
                {
                    ModelState.Clear();
                    return PartialView("LoginPopup", new LoginModel());
                }
            }
        }

【讨论】:

  • 此解决方案重定向到新页面。我想我会使用 gnome 的解决方案。我很惊讶 MVC2 中没有更简单的解决方案可以在不更改页面的情况下做到这一点。
  • 不,它不会重定向到新页面,如果您使用带有 ajax.actionlink() 的强类型部分视图,则在 Create() 中将结果返回到部分视图,结果会重新生成部分视图甚至只做 post ... [它会给你与使用 JSON 实现的结果相同的结果] ...
  • @dvlpr 局部视图在哪里显示?
  • 在这里你可以看到我正在使用 Ajax.BeginForm(),它在单击提交按钮时触发,根据此如果身份验证成功则将其重定向到用户的主页,否则清除 ModelState 并重新初始化登录模型。并且以同样的方式你可以使用 Ajax.ActionLink()
  • @dvlpr 非常感谢!太完美了!
【解决方案2】:

刚刚输入此内容,尚未对其进行测试,但基本想法是在客户视图中列出您的产品,并使用按钮为客户添加新产品。

为客户列出产品:

<table>
    <% foreach(var p in Customer.Products) { %>
    <tr>
        <td><%: p.Quantity %></td>
        <td><%: p.Name %></td>
    </tr>
    <% } %>
</table>
<p><%: Html.ActionLink("Add Product", "Create", new { controller = 'Products' }, new { id = 'addProduct'}) %>

<div id="dialog"></div>

要为客户添加新产品,您可以使用 jQuery UI 显示对话框;只需传递客户 ID

// 假设你已经包含了 jquery-ui

<script type="text/javascript">
$(document).ready(function() {
    $('#dialog').dialog({ 
        autoOpen : false,
        button : { 
            'Save' : function() {
                $.ajax({
                    url : $('#addProduct').attr('href'),
                    type : 'get'
                    success : function() { 
                        alert('Product added!');
                    }
                });
            }, 
            'Cancel' : function() {
                $('#dialog').dialog('close');
            }
        }
    });

    $('#addProduct').click(function() {
        var customerId = $('#CustomerId').val();
        $('#dialog').dialog('open');
        $('#Customer_Product_Id').val(customerId); // assuming there's a hidden field on the form
    });
});
</script>

在您的产品控制器中返回一个部分

public ActionResult Create() 
{
    List<Product> products = new List<Product>() { 
        new Product() { Id = 1, Name = "Rice" },
        new Product() { Id = 2, Name = 'Corn' }};
    ViewData.Add("Products", new SelectList(products, "Id", "Name", ""));
    Product product = new Product();
    if (Request.IsAjaxRequest()) 
    {
        return PartailView("_CreateOrEdit", product)
    }

    return View("Create", product);
}

_创建视图

<%: Html.TextBoxFor(model => model.Quantity) %>
<%: Html.DropDownList("Products") %>
<%: Html.HiddenFieldFor(model => model.Product.Customer.Id) %>

【讨论】:

  • 感谢您的代码,非常有趣!但是,当我使用它时,jQuery 对话框可见 2 秒,然后我被重定向到 Product/Create 并显示应该在对话框中的部分视图。
  • 哦......就像我说的,我没有在 Visual Studio 中梳理出来。您需要包含一个 return false;在点击事件上,否则它将跟随链接。我有一个基本上需要你的解决方案。看看我能不能给你挖出来;但它基本上遵循上述内容。
  • 我已经用 'return false;' 进行了测试但是这样一来,控制器就不会被调用,局部视图也不会被渲染......
  • 使用后确定:$('#dialog').load("/Product/Create"); $('#dialog').dialog('open');我有我想要的
  • 优秀。编程愉快!
猜你喜欢
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
  • 2012-02-19
  • 2010-11-15
  • 2017-11-09
  • 2011-06-24
  • 1970-01-01
相关资源
最近更新 更多