MVC5 Asp.net Is there a way to get the correct value from EditorFor for a subclass

给你一囗甜甜゛ 提交于 2019-12-02 21:22:33

问题


I have a class

public class Citizen
{
    public long ID { get; set; }
    public string Name { get; set; }
    public long CityID { get; set; }
    public string City { get; set; }
    public List<CitizenResource> Resources { get; set; }
}

I want to edit individual items in the Resources but the EditorFor doesn't set up the input correctly.

@for (int i = 0; i < Model.Resources.Count; i++ )
{ 
    @Html.BeginForm("EditResource", "Citizen")
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            <div class="form-group">
                <p class="form-control-static">
                    @Html.DisplayFor(model => model.Resources[i].Name)
                </p>
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Resources[i].CurrentAmount, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Resources[i].CurrentAmount, "", new { @class = "text-danger" })
                    <input type="hidden" name="ResourceID" value="@Model.Resources[i].ResourceID"/>
                    <input type="submit" value="Update" class="btn btn-default" />
                </div>
            </div>
        </div>
     }
}

What I get is name="Resources[0].CurrentAmount" which then doesn't map correctly to the CitizenResource class.

Can anyone help point me in the right direction?


回答1:


The expression you sent causes that name:

What I get is name="Resources[0].CurrentAmount" which then doesn't map correctly to the CitizenResource class.

@Html.EditorFor(model => model.Resources[i].CurrentAmount, new { htmlAttributes = new { @class = "form-control" } })

Instead have a partial view to edit an CitizenResource

@model CitizenResource

@using(Html.BeginForm("EditResource", "Citizen")){
            {
//The complete elements
@Html.EditorFor(model => model.CurrentAmount, new { htmlAttributes = new { @class = "form-control" } })
//The rest of the elements
}}



回答2:


Your code is creating multiple forms which is not good. The best way to handle this kind of scenario is the use of EditorTemplates. Checkout this link on how to do it. EditorFor() for a List of Complex Type (MVC)



来源:https://stackoverflow.com/questions/33089916/mvc5-asp-net-is-there-a-way-to-get-the-correct-value-from-editorfor-for-a-subcla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!