【问题标题】:How to save value checked in asp.net mvc and dropdownlist using c#?如何使用 c# 保存在 asp.net mvc 和下拉列表中检查的值?
【发布时间】: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


【解决方案1】:

检查时只有复选框值通过

如果您的值不是true or false,则在选中时通常会通过每个复选框

设置值复选框

<input type="checkbox" id="yourInputName" name="yourInputName" value="yourvalue" />

在控制器中获取值

public ActionResult DietOptions(string yourInputName) // your datatype

您可以通过Request.Form获得价值

var form = Request.Form;
var value = form["yourInputName"]; // can you cast for your dataType

但是如果你的数据类型 Bool 必须设置默认值,因为如果不检查通过 null 可以通过 False

您可以通过某种方式解决购买问题

你可以通过普通参数传递值

<input type="checkbox" id="Vegetarian " name="Vegetarian " value="true" /> // if check ed pass true else pass null, you can change true to false when checked

控制器

public ActionResult DietOptions(bool Vegetarian = false) // if checked true else false

**或者你可以在你的实体中设置默认值**

public class DietViewModel
{
     ....
     [Display(Name = "Vegetarian")]
     [Range(typeof(bool), "true", "true")]
     public bool Vegetarian { get; set; } = false;
     ....

}

另一种方式可以使用Partial Class 设置默认值而不影响原始类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多