【问题标题】:Asp.net MVC get fully qualified URL to an action methodAsp.net MVC 获取操作方法的完全限定 URL
【发布时间】:2012-03-07 09:51:53
【问题描述】:

项目中的现有代码正在使用 Url.Action 获取完全限定的 URL 以显示在对话框中。所以它有一个控制器函数,看起来像:

public ActionResult CheckItem(bool isCorrect, string id){}

然后 Url.Action 就是:

Url.Action("CheckItem", new { isCorrect =  true, id = 2})

现在这一切都很好。但我必须发送一个对象列表,我通过提交表单来完成这一切。

所以我的问题是:有没有办法使用 Url.Action 提交表单?如果不是,那么提交我的表单并取回 URL 的最佳方式是什么。

谢谢。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    我不完全了解您需要什么,但我认为您可能使用复选框或其他方式从用户那里选择了一些项目。

    答案可能在此链接上:CheckboxList in MVC3.0

    基本上你要做的是:创建一个接收 List 或 IEnumerable 项的 Action,然后将你的表单 POST 到该 Action。

    我也做了一个示例代码,可以提供帮助:

    你可以有一个 Item 模型:

    using System;
    
    namespace SandboxMvcApplication.Models
    {
        public class Item
        {
            public int Id { get; set; }
            public string Title { get; set; }
        }
    }
    

    您的控制器可能是:

    public class HomeController : Controller
    {
        List<Item> itemList = new List<Item>() {
                new Item() { Id = 1, Title = "Item 1" },
                new Item() { Id = 2, Title = "Item 2" },
                new Item() { Id = 3, Title = "Item 3" }
            };
    
        public ActionResult Index()
        {
            return View(itemList);
        }
    
        public ActionResult ProcessForm(int[] items)
        {
            var selectedItems = new List<Item>();
            foreach (var item in items)
            {
                selectedItems.AddRange(itemList.Where(i => i.Id == item));
            }
    
            return View("Success", selectedItems);
        }
    }
    

    一个索引视图(~/Views/Home/Index.cshtml):

    @model List<SandboxMvcApplication.Models.Item>
    
    @{
        ViewBag.Title = "Home Page";
    }
    
    <form action="@Url.Action("ProcessForm")" method="post">
        <ul>
            @foreach (var item in Model)
            {
                <li><input type="checkbox" name="items" value="@item.Id" />@item.Title</li>
            }
        </ul>
    
        <input type="submit" value="Send selected items"/>
    </form>
    

    最后是一个成功视图,显示用户选择了哪些项目:

    @model List<SandboxMvcApplication.Models.Item>
    
    @{
        ViewBag.Title = "Success";
    }
    
    <h2>Success: Selected items were</h2>
    
    <ul>
    @foreach (var item in Model)
    {
        <li>@item.Id => @item.Title</li>            
    }
    </ul>
    

    【讨论】:

    • 您好 Felipe 感谢您的回复。我需要获取 ActionResult 返回,以便我可以将其作为参数传递给 jquery 函数,该函数将在对话框中显示返回的页面,而不是更改当前网页。所以以前我使用过: onclick ="'myjquery.showInDialog(Url.Action("CheckItem", new { isCorrect = true, id = 2}))'" 然后在弹出窗口中显示网页。但是现在我必须同时提交一个表单,所以我想知道我如何才能做到这一点并得到回复。
    猜你喜欢
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2017-07-09
    • 1970-01-01
    • 2021-09-13
    相关资源
    最近更新 更多