简体   繁体   English

绑定模型的问题

[英]Issues with Binding Model to view

When attempting to bind a model to a view, I'm getting a 404 error. 尝试将模型绑定到视图时,我收到404错误。 The ActionResult is called 'SortDesc' but the view is just a standard 'Index' view. ActionResult被称为“SortDesc”,但视图只是一个标准的“索引”视图。 I understand that this isn't loading because the there is now view called 'SortDesc'. 我知道这不是加载,因为现在有一个名为'SortDesc'的视图。 However I have two buttons one to sort data ascending and one to sort data decending hence the two seperate functions. 但是我有两个按钮,一个用于对数据进行排序,另一个用于对数据进行排序,从而降低两个独立的功能。 I'm just not sure what the best solution would be here, either to continue with the two seperate functions and somehow pass in the correct view to load or to create a new, single HttpPost function on Index that will know which button has been clicked and sort accordingly. 我只是不确定这里最好的解决方案是什么,要么继续使用两个单独的函数,要么以某种方式传递正确的视图来加载或在Index上创建一个新的单个HttpPost函数,该函数将知道哪个按钮已被点击并相应地排序。 Here's the code I have so far: 这是我到目前为止的代码:

Models: 楷模:

public class NumberSetList
{
    public int NumberSetListId { get; set; }
    public List<NumberList> Numbers { get; set; }

    public string SortOrder { get; set; }
}

public class NumberList
{
    public int NumberListId { get; set; } 
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public int Number3 { get; set; }
    public int Number4 { get; set; }
    public int Number5 { get; set; }
    public string SortOrder { get; set; }
}

Razor: 剃刀:

@{
    ViewBag.Title = "csi media web test";
}

<div class="jumbotron">
    <h1>csi media web test</h1>
    <p class="lead">Liane Stevenson</p>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-info">
            <div class="panel-heading"><i class="glyphicon glyphicon-arrow-right"></i> Enter Your Four Numbers</div>
            <div class="panel-body">
                <form class="form-inline">
                    <div class="col-md-9">
                        <div class="form-group">
                            <label class="sr-only" for="number1">1st Number</label>
                            <input type="number" class="form-control" id="number1" name="Number1" placeholder="#1">
                        </div>
                        <div class="form-group">
                            <label class="sr-only" for="number2">2nd Number</label>
                            <input type="number" class="form-control" id="number2" name="Number2" placeholder="#2">
                        </div>
                        <div class="form-group">
                            <label class="sr-only" for="number3">3rd Number</label>
                            <input type="number" class="form-control" id="number3" name="Number3" placeholder="#3">
                        </div>
                        <div class="form-group">
                            <label class="sr-only" for="number4">4th Number</label>
                            <input type="number" class="form-control" id="number4" name="Number4" placeholder="#4">
                        </div>
                    </div>
                    <div class="col-md-3 text-right">
                        <a class="btn btn-default" href="@Url.Action("SortDesc", "Home")"><i class="glyphicon glyphicon-arrow-down"></i> Sort Desc</a>
                        <a class="btn btn-default" href="@Url.Action("SortAsc", "Home")"><i class="glyphicon glyphicon-arrow-down"></i> Sort Asc</a>
                    </div>
                </form>
                <p>
                    @if (Model != null)
                    {
                        foreach (int number in Model.Numbers)
                        {
                            <span class="label label-info">@number</span>
                        }
                    }   
                </p>
            </div>
        </div>
    </div>
</div>

Home Controller: 家庭控制器:

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

[HttpPost]
public ActionResult SortDesc([Bind(Include = "Number1, Number2, Number3, Number4")] NumberSetList model)
{

    if (!ModelState.IsValid)
    {
        return View();
    }
    else
    {
        NumberSetList list = new NumberSetList();
        List<int> numbers = new List<int>();
        numbers.Add(model.Number1);
        numbers.Add(model.Number2);
        numbers.Add(model.Number3);
        numbers.Add(model.Number4);
        numbers.OrderByDescending(i => i);
        list.SortOrder = "Desc";
        return View(list);
    }

}

Try this 试试这个

public class NumberSetList {
    public int NumberSetListId { get; set; }
    public List<NumberSetItem> Numbers { get; set; }
    public string SortOrder { get; set; }
}

public class NumberSetItem {
    public int Value { get; set; }
}

, use for loop to create inputs for the numbers ,使用for循环为数字创建输入

 @using (Html.BeginForm()) {
    <div class="col-md-9">
        <div class="form-group">
            @if (Model != null && Model.Numbers != null) {
                @for (int i = 0; i < Model.Numbers.Count; i++) {
                    <div class="form-group">
                        @Html.LabelFor(m => m.Numbers[i].Value, "Number " + (i+1).ToString())
                        @Html.TextBoxFor(m => m.Numbers[i].Value, new { @class = "form-control" })
                    </div>
                }
               <div class="col-md-3 text-right">
                   <input id="SortOrder" value="Desc" type="button" class="btn btn-default"><i class="glyphicon glyphicon-arrow-down"></i> Sort Desc</input>
                   <input id="SortOrder" value="Asc" type="button" class="btn btn-default"><i class="glyphicon glyphicon-arrow-down"></i> Sort Asc</input>
               </div>
            }
        </div>
    </div>
}

And in the View 并在视图中

[HttpPost]
public ActionResult Index(NumberSetList model) {
    if (!ModelState.IsValid) {
        return View();
    } else {
        var numbers = model.SortOrder == "Desc" ?
            model.Numbers.OrderByDescending(n => n.Value) : 
            model.Numbers.OrderBy(n => n.Value);
        model.Numbers = numbers.ToList();
        return View(model);
    }
}

You can fix the issue using a variety of techniques. 您可以使用各种技术解决问题。

Pass the name of the view into the View method like this: 将视图的名称传递给View方法,如下所示:

return View("Index", list);

The View method has many overloads and you can see them all here . View方法有很多重载,你可以在这里看到它们。 It is nice to get yourself familiar with the overloads for scenarios like the one you are facing. 熟悉您所面临的场景的重载是很好的。

If your view is not in the same folder as the action, you will need to pass the path for the view instead of just the name. 如果您的视图与操作不在同一文件夹中,则需要传递视图的路径而不仅仅是名称。

Another way is to have a single action and you can call this one Index as well but this one will take a model as an argument. 另一种方法是只有一个动作,你也可以调用这个索引,但是这个将把模型作为参数。 Your model can have the numbers and an enum for sort: Desc, Asc. 您的模型可以包含数字和枚举:Desc,Asc。 In your action method you can analyze the model, and do whatever is needed. 在您的操作方法中,您可以分析模型,并执行所需的操作。

The approach with the model is the one I prefer. 模型的方法是我喜欢的方法。

EDIT 编辑

I just noticed you have this line of code in your view: 我刚刚注意到你在视图中有这行代码:

<a class="btn btn-default" href="@Url.Action("SortDesc", "Home")"><i class="glyphicon glyphicon-arrow-down"></i> Sort Desc</a>

That will trigger an HTTP GET and therefore it will not hit your SortDsc action method. 这将触发HTTP GET,因此它不会命中您的SortDsc操作方法。 Remove POST from your action method or use a post technique (Form) to hit your action method using POST. 从您的操作方法中删除POST或使用post技术(Form)使用POST命中您的操作方法。

EDIT 2 编辑2

Honestly what you are doing is far simpler than you are making it. 老实说,你正在做的事情远比你做的要简单得多。 First thing is when you are using Url.Actio you are not passing nothing to your action method so how will it know about the numbers? 首先,当你使用Url.Actio时,你没有向你的动作方法传递任何内容,那么它将如何知道这些数字呢? I would normally call my action method using AJAX and get the result and display the result. 我通常会使用AJAX调用我的action方法并获取结果并显示结果。

Without AJAX, you need to use one form for ascending and one for descending. 如果没有AJAX,您需要使用一个表单进行升序,一个表单用于降序。 Or you can use a radio button so user can select the order first. 或者您可以使用单选按钮,以便用户可以先选择订单。

Here is some code to do it using radio buttons. 以下是使用单选按钮执行此操作的一些代码。

Action: 行动:

[HttpPost]
public ActionResult SortDesc([Bind( Include = "Number1, Number2, Number3, Number4, SortOrder" )] NumberList model) {

   if( !ModelState.IsValid ) {
      return View("Index");
   }
   model.Numbers = new List<int>();
   model.Numbers.Add( model.Number1 );
   model.Numbers.Add( model.Number2 );
   model.Numbers.Add( model.Number3 );
   model.Numbers.Add( model.Number4 );
   model.Numbers.Add( model.Number5 );
   if (model.SortOrder == "Desc" ) {
      model.Numbers = model.Numbers.OrderByDescending( i => i ).ToList();
   }
   else {
      model.Numbers = model.Numbers.OrderBy( i => i ).ToList();
   }

   return View("Index", model);

}

Model: 模型:

public class NumberList {
   public int Number1 { get; set; }
   public int Number2 { get; set; }
   public int Number3 { get; set; }
   public int Number4 { get; set; }
   public int Number5 { get; set; }
   public int NumberListId { get; set; }
   public List<int> Numbers { get; set; }
   public string SortOrder { get; set; }
}

View: 视图:

@using( Html.BeginForm( "SortDesc", "Home", FormMethod.Post ) ) {
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-info">
            <div class="panel-heading"><i class="glyphicon glyphicon-arrow-right"></i> Enter Your Four Numbers</div>
            <div class="panel-body">
                <form class="form-inline">
                    <div class="col-md-9">
                        <div class="form-group">
                            <label class="sr-only" for="number1">1st Number</label>
                            <input type="number" class="form-control" id="number1" name="Number1" placeholder="#1">
                        </div>
                        <div class="form-group">
                            <label class="sr-only" for="number2">2nd Number</label>
                            <input type="number" class="form-control" id="number2" name="Number2" placeholder="#2">
                        </div>
                        <div class="form-group">
                            <label class="sr-only" for="number3">3rd Number</label>
                            <input type="number" class="form-control" id="number3" name="Number3" placeholder="#3">
                        </div>
                        <div class="form-group">
                            <label class="sr-only" for="number4">4th Number</label>
                            <input type="number" class="form-control" id="number4" name="Number4" placeholder="#4">
                        </div>
                        <div class="form-group">
                            <input type="radio" class="form-control" id="number4" name="SortOrder" value="Desc">
                        </div>
                        <div class="form-group">
                            <input type="radio" class="form-control" id="number4" name="SortOrder" value="Asc">
                        </div>
                    </div>

                    <div class="col-md-3 text-right">
                        <button class="btn btn-default"><i class="glyphicon glyphicon-arrow-down"></i> Sort </button>
                        @*<a class="btn btn-default"><i class="glyphicon glyphicon-arrow-down"></i> Sort Asc</a>*@
                    </div>
                </form>
                <p>
                    @if( Model != null ) {
                        foreach( int number in Model.Numbers ) {
                        <span class="label label-info">@number</span>
                        }
                    }
                </p>

            </div>
        </div>
    </div>
</div>

}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM