0

Models

public class IntegerList
{
    public int IntegerListID { get; set; }
    public string Direction { get; set; }
    public long Performance { get; set; }
    public virtual ICollection<Integer> Integers { get; set; }
}

public class Integer
{
    public int IntegerID { get; set; }
    [Required(ErrorMessage = "An integer is Required")]
    [Range(0, 9999999, ErrorMessage = "Enter an integer")]
    public int IntegerValue { get; set; }
    public int IntegerListID { get; set; }
    public virtual IntegerList IntegerList { get; set; }
}

The above models are for an application that sorts a range of integers into ascending or descending order and calculates the time taken to perform the sort.

The integers are entered into textboxes by the user who can add or remove them using jquery.

I've got the application working by passing formcollection to the controller, splitting the string of integers into an array of integer values to be added to IntegerList.Integers.

However, I'm looking for a more elegant strongly-typed solution.

ViewModel

public class IntegerViewModel
{
    [UIHint("Integers")]
    public IEnumerable<Integer> Integers { get; set; }
    public string Direction { get; set; }
}

Where I'm struggling is adding Integers.IntegerValues to the view so they can be passed to the controller via the viewmodel. I also need to increment/decrement each IntegerValue textbox value as it is added/removed by jquery. I'm not sure I'm approaching this from the right angle.

I hope that's clear. Thanks for your assistance.

Razor

    <form method="post">
        <div id="integers">
            @Html.Label("Enter Integers")
            <div class="integer">
                @Html.EditorFor(model => model.Integers)
                <a href="#" id="addInt">Add Integer</a>
            </div>
        </div>
        @Html.Label("Sort Direction")
        <div>
            @Html.DropDownListFor(model => model.Direction, new[] {
                new SelectListItem() {Text = "Ascending", Value = "Ascending"},
                new SelectListItem() {Text = "Descending", Value = "Descending"}
            })

            <input class="button" type="submit" value="Submit" />
        </div>
    </form>

Editor Template (for Integers)

@model Integer

@Html.EditorFor(m => m.IntegerValue)
4

1 回答 1

0

让我总结一下。

只要您使用 JavaScript (jQuery) 添加和删除值(整数),您就不会在那里找到任何强类型的解决方案。

因此,当您使用 jquery 添加整数编辑器时,您应该根据 ASP.NET MVC 合同呈现适当的 HTML。

大卫的评论非常有价值。看看这个链接。http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

在这里,您可以看到应如何呈现 HTML 以在服务器上接收不同类型的数据(ASP.NET MVC 操作)。

您还可以检查您的 EditorFor 输出并像使用 MVC 渲染一样渲染 HTML。

最后,这是关于 ASP.NET MVC 中的动态表单字段的问题。ASP.NET MVC 动态表单

希望这可以帮助。

于 2013-10-04T12:02:44.930 回答