但是我无法以这种方式提交表单,因为我的此表单操作模型如下所示:
public string Title { get; set; } // First input
public string Description { get; set; } // Second input
public string SportsmanId { get; set; } // Not used
public List<WorkoutExerciseParam> WorkoutExerciseParams { get; set; } // Items, combined from list items (show on form screenshot)
public SelectList AvailableSportsmans { get; set; } // Dropdown list
所以,如果我不能提交,我写了 JS 代码来构建和发布一致的模型:
$(document)
.ready(function() {
$("#submit").click(function() {
var exerciseList = [];
/* Assemble exerciseList from OL and UL items */
var title = $("input#Title").val();
var description = $("input#Description").val();
var sportsmanId = $("select#SportsmanId").val();
$.post('@Url.Action("Create", "Workout")',
{
Title: title,
Description: description,
SportsmanId: sportsmanId,
WorkoutExerciseParams: exerciseList
});
});
});
这段代码工作正常,但我无法在操作完成后重定向(就像我刚提交表单时一样):
然后,我重写 JS 代码,以便它构造一个带有隐藏输入的新隐藏表单并提交它。但我不知道如何创建输入列表(第一个代码示例中的列表)。
问题:
What is the best practice to submit data to ASP.NET Controller's Action throw JS that I can use RedirectToAction() and View() methods? Do I need construct form (how can I do a list of objects) or how handle RedirectToAction() and View() method in JS?
You should be making a normal submit rather that ajax if you want to redirect (or be able to return the view and display validation errors if ModelState
is invalid. There is no point using ajax, since ajax calls do not redirect.
You have not shown how your dynamically generating the inputs associated with your WorkoutExerciseParam
collection, but they just need to be named correctly with indexers so that they will be bound by the DefaultModelBinder
. The format needs to be
<input name="WorkoutExerciseParams[0].SomeProperty" .... />
<input name="WorkoutExerciseParams[0].AnotherProperty" .... />
<input name="WorkoutExerciseParams[1].SomeProperty" .... />
<input name="WorkoutExerciseParams[1].AnotherProperty" .... />
....
您可以使用 javascript 生成它,但更好的解决方案是使用BeginCollectionItem()
在答案中讨论的方法,它为您提供字符串类型绑定、动态添加项目的客户端验证以及删除项目的能力
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句