我有一个表单,它有一个文本框(称为名称)和一组复选框和一组收音机。我想发送文本框的值,一个仅包含选中复选框的值和选中的单选框值的数组。我知道我可以为此使用 jquery ajax 语法,但我想用 Ajax.BeginForm 来做。据我所知,Ajax 选项 OnBegin 可能是关键,但我无法弄清楚如何在请求进入操作之前更改它。
****编辑:****
我已经根据斯蒂芬的回答重新编写了代码,但我仍然遇到问题,只是让它正确渲染。这是代码:
public class RecipeSearch
{
public List<Recipe> Recipe { get; set; }
public List<Meal> MealSettings { get; set; }
public List<Ingredient> MainIngredient { get; set; }
}
public class Meal
{
public int Id { get; set; }
public bool Value { get; set; }
public string DisplayName { get; set; }
}
public ActionResult Search()
{
RecipeSearch recipe = new RecipeSearch();
recipe = recipeSearchDetails(null, null);
recipe.Recipe = dbContext.Recipes
.OrderBy(r => r.name)
.Where(r => r.name.Contains("") || string.IsNullOrEmpty(""))
.ToList();
RecipeSearch recipe = new RecipeSearch();
recipe.MealSettings = new List<Meal>();
var meals = dbContext.MealCategories
.OrderBy(r => r.name)
.ToList();
var MainIngredient = dbContext.Maincategories
.OrderBy(r => r.name).ToList();
foreach (var item in meals)
{
recipe.MealSettings.Add(new Meal { DisplayName = item.name, Value = true, Id = item.mealCategoryId });
}
recipe.Recipe = dbContext.Recipes
.OrderByDescending(r => r.MealCategory.name)
.Where(mc => mc.MealCategory.name == mealCategory || (mealCategory == null))
.Where(m => m.Ingredients.FirstOrDefault().SubCategory.name == mainIngredient || (mainIngredient == null)).ToList();
return PartialView("_search", recipe);
}
模型:
@model RecipeTrackerMVC.Models.Search.RecipeSearch
@for (int i = 0; i < Model.MealSettings.Count(); i++)
{
<li>
@Html.CheckBoxFor(r => Model.MealSettings[i].Value)
@Html.LabelFor(r => Model.MealSettings[i].Value, Model.MealSettings[i].DisplayName)
@Html.HiddenFor(r => Model.MealSettings[i].Id)
</li>
}
浏览器为每顿饭呈现以下内容:
名字就该这么草率吗?
除此之外,我还进行了 AJAX 调用,这是我得到的数据。除了 id 12 之外,所有项目都未选中 - 但由于某种原因,一个项目有两个值,我不知道为什么。另外,我认为使用这种样式(checkboxfor),只有被选中的项目才应该在请求中发送?
name:s
allCategories:false
MealSettings[0].Value:false
MealSettings[0].Id:7
MealSettings[1].Value:false
MealSettings[1].Id:8
MealSettings[2].Value:false
MealSettings[2].Id:9
MealSettings[3].Value:false
MealSettings[3].Id:1
MealSettings[4].Value:false
MealSettings[4].Id:10
MealSettings[5].Value:false
MealSettings[5].Id:11
MealSettings[6].Value:false
MealSettings[6].Id:12
MealSettings[7].Value:true
MealSettings[7].Value:false
MealSettings[7].Id:4
MealSettings[8].Value:false
MealSettings[8].Id:3
MealSettings[9].Value:false
MealSettings[9].Id:17
MealSettings[10].Value:false
MealSettings[10].Id:2
allIngredients:all
allIngredients:false
startTime:
endTime:
prepTime:0
cookTime:0
standTime:0
X-Requested-With:XMLHttpRequest
当我使用这种语法进行 Ajax 调用时,模型显示为 null:
public ActionResult Search(IEnumerable<RecipeSearch> model)