【发布时间】:2020-11-10 19:28:57
【问题描述】:
我需要一些帮助,我有 Razor 上的国家列表和复选框。我需要找到一种方法将这些从数据库保存到我的表中。这是我在下面执行此操作的逻辑;我想为两者保存它们,这意味着对于国家列表,如果为该国家/地区选择它必须存储数据库并且与复选框相同。卡住了,请根据下面的帮助队友。如果有控制器必须添加,那么我会使用它但不知道如何。
控制器
//POST /Home/DietaryListOptions
[HttpPost]
public ActionResult DietOptions(DietViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return View("Success");
}
加载世界各国列表
private List<RegistrationTrainingForm> LoadData()
{
List<RegistrationTrainingForm> lst = new List<RegistrationTrainingForm>();
try
{
string line = string.Empty;
string srcFilePath = "Content/files/country_list.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader src = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
// while to read the file
while ((line = src.ReadLine()) != null)
{
RegistrationTrainingForm infoLst = new RegistrationTrainingForm();
string[] info = line.Split(',');
//Setting
infoLst.Country_Id = Convert.ToInt32(info[0].ToString());
infoLst.Country_Name = info[1].ToString();
lst.Add(infoLst);
}
src.Dispose();
src.Close();
}
catch (Exception ex)
{
Console.Write(ex);
}
return lst;
}
国家/地区列表
private IEnumerable<SelectListItem> GetCountryList()
{
SelectList listcn = null;
try
{
var list = this.LoadData().Select(p => new SelectListItem
{
Value = p.Country_Id.ToString(),
Text = p.Country_Name
});
listcn = new SelectList(list, "Value", "Text");
}
catch (Exception ex)
{
throw ex;
}
return listcn;
}
视图模型
public class DietViewModel
{
[Display(Name = "None")]
[Range(typeof(bool), "true", "true")]
public bool None { get; set; }
[Display(Name = "Vegetarian")]
[Range(typeof(bool), "true", "true")]
public bool Vegetarian { get; set; }
[Display(Name = "Vegan")]
[Range(typeof(bool), "true", "true")]
public bool Vegan { get; set; }
[Display(Name = "Halaal")]
[Range(typeof(bool), "true", "true")]
public bool Halaal { get; set; }
[Display(Name = "Other")]
[Range(typeof(bool), "true", "true")]
public bool Other { get; set; }
}
public class DropDownViewModel
{
public int Country_Id { get; set; }
public string Country_Name { get; set; }
}
查看
<div class="form-check">
@Html.CheckBoxFor(model => model.DietMain.Vegetarian, new { @class = "form-check-input" })
<label class="form-check-label" for="@Html.IdFor(m => m.DietMain.Vegetarian)">Vegetarian</label>
</div>
<div class="form-check">
@Html.CheckBoxFor(model => model.DietMain.Vegan, new { @class = "form-check-input" })
<label class="form-check-label" for="@Html.IdFor(m=>m.DietMain.Vegan)">Vegan</label>
</div>
【问题讨论】:
-
希望您将每个复选框的值传递给控制器,然后保存您的数据库?
-
@Zanyar 是的,我想要围绕它的逻辑
标签: c# mysql asp.net-mvc entity-framework bootstrap-4