当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - .net: Adding fields to a form does not trigger validation

问题描述:

When adding fields to a form that has been parsed by jquery-unobtrusive, we're not able to add more fields since these are not being included in the validation. What are we missing?

WallViewModel.cs

public class WallViewModel

{

public int BuildingId { get; set; }

public List<WallModel> Walls { get; set; }

}

public class WallModel

{

[HiddenInput(DisplayValue = false)]

[Display(Name = "#")]

public int Id { get; set; }

[Required]

[Display(Name = "Wall name")]

public string Name { get; set; }

[Required]

[RegularExpression(RegularExpressions.Numbers, ErrorMessage = ValidationErrorMessages.Numbers)]

[Display(Name = "Surface m\u00B2")]

public double Area { get; set; }

}

BuildingController.cs

public BuildingController : Controller {

public async Task<PartialViewResult> CreateWall(int counter)

{

return PartialView("Wall/AddWall", new WallModel {Counter = counter, IsUpdated = true});

}

}

Wall.cshtml

@{var counter = 1}

@using (Html.BeginForm("UpdateWall", "Building", FormMethod.Post, new {id = "editWallsForm" }))

{

<table id="editWallTable" class="table table-striped">

<tr>

<th>

#

</th>

<th>

Wall name

</th>

<th>

Surface (m<sup>2</sup>)

</th>

</tr>

@{

for (var i = 0; i < Model.Walls.Count; i++)

{

Model.Walls[i].Counter = counter;

var index = Model.Walls[i].Counter - 1;

<tr id="[email protected][i].Id">

<td>

@Html.DisplayFor(model => model.Walls[i].Counter)

@Html.HiddenFor(model => model.Walls[i].Id, new { Value = Model.Walls[i].Id, Name = "walls[" + index + "]" + ".Id" })

@Html.HiddenFor(model => model.Walls[i].IsUpdated, new { Value = Model.Walls[i].IsUpdated, Name = "walls[" + index + "]" + ".IsUpdated", @class = "IsUpdated" })

</td>

<td>

@Html.TextBoxFor(model => model.Walls[i].Name, new { @class = "form-control input-sm", Name = "walls[" + index + "]" + ".Name"})

</td>

<td>

@Html.TextBoxFor(model => model.Walls[i].Area, new { @class = "form-control input-sm", Name = "walls[" + index + "]" + ".Area"})

</td>

</tr>

counter++;

}

}

</table>

@Html.ValidationSummary()

}

<button id="submitWall">Submit</button>

<script>

$.validator.unobtrusive.parse($('#editWallsForm'));

var counter = @counter;

$('.addWallButton').on('click', function() {

$.ajax({

url: addWallUrl

data: {counter: counter}

})

.done(function (response) {

$('tbody').append(response);

counter++;

$('#editWallsForm').validate();

}.bind(this));

});

$('#submitWall').on('click', function() {

if (this.$editWallsForm.valid()) {

}

else {

}

})

</script>

分享给朋友:
您可能感兴趣的文章:
随机阅读: