使用ASP.NET MVC在单个表单中插入多行

时间:2017-07-11 15:42:44

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-5

这里我的问题是,用户输入区域详细信息,例如地名,noofplaces,在此处创建用户详细信息后,用户输入noofplaces,因此有多少人输入(10,20甚至100)应该创建许多行。

这是为我工作的代码

区域模型

`public class Area
{
    [Key]
    public int AreaID { get; set; }

    public string ParkingPlaceName { get; set; }
    public int NoOfParkingPlaces { get; set; }

    [DataType(DataType.Currency)]
    public decimal MinimumCharges { get; set; }
    public string Address { get; set; }
    [Precision(25,22)]
    public decimal Latitude { get; set; }
    [Precision(25,22)]
    public decimal Longitude { get; set; }

    public virtual ICollection<Car> Cars { get; set; }
    public virtual ICollection<ParkingPlace> ParkingPlaces { get; set; }
}

}`

ParkingPlace模型

public class ParkingPlace
{
    [Key]
    public int ParkID { get; set; }
    public string PlaceId { get; set; }
    public int AreaID { get; set; }

    public virtual ICollection<Car> Cars { get; set; }
    public virtual Area Areas { get; set; }
}

控制器代码

    public ActionResult Create(string areaName)
    {
        Area area = db.Areas.SingleOrDefault(x => x.ParkingPlaceName == areaName);
        return View(area);
    }

    [HttpPost]
    public ActionResult Create([Bind(Include = "ParkID,PlaceId,AreaID")] List<Place> place)
    {
        if (ModelState.IsValid)
        {
            foreach(var i in place)
            {
                db.Places.Add(i);
            }
            db.SaveChanges();
            return RedirectToAction("Index", "Area");
        }
        return View(place);
    }

查看代码

@model CarParking.Models.Area

@using (Html.BeginForm("Create","ParkingPlace", FormMethod.Post)) 
{
    <hr />
    <table>
        <tr>
            <th>Place ID's</th>
            <th>Area ID's</th>
        </tr>

        @for (int i = 0; i < Model.NoOfParkingPlaces; i++)
        {
            <tr class="form-group">
                <td>
                    @Html.TextBox("[" + i + "].PlaceId", "P.Id_" + i + "", htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessage("[" + i + "].PlaceId", "", new { @class = "text-danger" })
                </td>
                <td>
                    @Html.TextBox("[" + i + "].AreaID", Model.AreaID, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessage("[" + i + "].AreaID", "", new { @class = "text-danger" })
                </td>
                <td>
                    @Html.Hidden("[" + i + "].PlaceId_Status", false)
                    @Html.ValidationMessage("[" + i +"].PlaceId_Status", "", new { @class = "text-danger"})
                </td>

            </tr>

        }
    </table>
    <p>
       <input type="submit" value="Create" class="btn btn-default" />
    </p>

 }

0 个答案:

没有答案