从下拉列表MVC

时间:2016-12-23 17:21:39

标签: c# model-view-controller asp.net-mvc-5

我正在开发一个应用程序asp.net MVC,它有一个文本框和两个下拉列表。用户可以输入数值并从 - 到列表中进行选择以进行处理。我的问题是尝试验证下拉列表,因为我尝试使用所需的验证但不起作用。我还尝试在发送空值时检查下拉列表,但错误验证不起作用!

错误类型:

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'fromCurrency.Name'.

Contorller

 [HttpPost]
        public ActionResult Index(Currencies cur)
        {
            if (ModelState.IsValid)
            {



                if (String.IsNullOrWhiteSpace(cur.fromCurrency.Name) || String.IsNullOrWhiteSpace(cur.toCurrency.Name))
                {
                    ModelState.AddModelError(string.Empty, "you can not leave the empty dropdown please select any of these");
                }


                else
                {

                    var fromCurrencyList = CurrenciesClient.GetFromCurrencyListAsync().Result;

                    ViewBag.FromCurrencies = new SelectList(fromCurrencyList, "CurrencyCode", "Name");

                    var ToCurrencyList = CurrenciesClient.GetToCurrencyListAsync().Result;

                    ViewBag.ToCurrencies = new SelectList(ToCurrencyList, "CurrencyCode", "Name");


                    var fromcurrname = cur.fromCurrency.Name;
                    string tocurrname = cur.toCurrency.Name;

                    //rate is taking by passing both dropdown currency code
                    decimal rate = CurrenciesClient.GetConversionRate("Currencies/GetConversionRate?fromcurrname=" + fromcurrname + "&tocurrname=" + tocurrname).Result;
                    ViewBag.TheResult = cur.CurrencyToConvert * rate;


                }

            }
            return View();
        }

索引视图

@model ViewModel.Currencies

@{
    ViewBag.Title = "Index";
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

    <div id="ConversionSection">

        <form class="form-horizontal" method="post" id= "CurrencyConversion" action="/Currency/Index">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
             <div class="form-group">
                <label class="col-sm-4 control-label">
                    @Html.LabelFor(m => m.CurrencyToConvert, "Enter Currency")
                </label>
                <div class="col-sm-4">
                    @Html.EditorFor(m => m.CurrencyToConvert, new { @class = " form-control" })
                    @*@Html.ValidationMessageFor(m => m.CurrencyToConvert)*@
                    @Html.ValidationMessageFor(m => m.CurrencyToConvert, "", new { @class = "text-danger" })


                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label">
                    @Html.LabelFor(model => model.fromCurrency.Name, "From Currency")
                </label>
                <div class="col-sm-4">
                    @Html.DropDownListFor(m => m.fromCurrency.Name, ViewBag.FromCurrencies as SelectList, "--select--", new { @class = " form-control" })
                    @Html.ValidationMessageFor(model => model.fromCurrency.Name)

                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label">
                    @Html.LabelFor(model => model.toCurrency.Name, "To Currency")
                </label>
                <div class="col-sm-4">
                    @Html.DropDownListFor(m => m.toCurrency.Name, ViewBag.ToCurrencies as SelectList, "--select--", new { @class = "form-control" })
                    @*@Html.ValidationMessageFor(model => model.toCurrency.Name)*@

                    @Html.ValidationSummary(false, "", new { @class = "text-danger" })


                </div>
            </div>

            <div class="form-group">
                     <label class="col-sm-4 control-label">
                         @Html.LabelFor(l => l.ConvertedCurrency, "Value")
                     </label>
                     <div class="col-sm-4">
                         @Html.Editor("TheResult", new { @class = " form-control" })
                     </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-4">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </div>

        </form>


    </div>

Currencies.cs

    public class Currencies
    {
        [Required]
        [DataType(DataType.Currency)]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public decimal CurrencyToConvert { get; set; }


        public Currency fromCurrency { get; set; }

        public Currency toCurrency { get; set; }

        public double ConvertedCurrency { get; set; }

    }

1 个答案:

答案 0 :(得分:1)

如果您的模型状态无效,则不会返回任何内容。因此viewbag.FromCurrenciesViewbag.ToCurrencies应该在if (ModelState.IsValid)之外。如果在if(ModelState.IsValid)空值之后您不会添加Viewbag属性代码,您将获得此异常。我在这里写httppost方法中的重构代码。

[HttpPost]
        public ActionResult Index(ConvertCurrencyViewModel cur)
        {
            if (ModelState.IsValid)
            {

                    string fromcurrname = cur.fromCurrency.Name;
                    string tocurrname = cur.toCurrency.Name;

                    //rate is taking by passing both dropdown currency code
                    decimal rate = CurrencyClient.GetConversionRate("Currency/GetConversionRate?fromcurrname=" + fromcurrname + "&tocurrname=" + tocurrname).Result;
                    ViewBag.result = cur.CurrencyToConvert * rate;

            }
                //getting this select list value form Currency client class
                var fromCurrencyList = CurrencyClient.GetFromCurrencyListAsync().Result;

                ViewBag.FromCurrencies = new SelectList(fromCurrencyList, "CurrencyCode", "Name");

                var ToCurrencyList = CurrencyClient.GetToCurrencyListAsync().Result;

                ViewBag.ToCurrencies = new SelectList(ToCurrencyList, "CurrencyCode", "Name");

                return View();

        }

并修改你的类似这样的类来显示验证错误。

public class Currencies
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter amount to convert")]
        [DataType(DataType.Currency)]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public decimal CurrencyToConvert { get; set; }


        [Required(AllowEmptyStrings = false, ErrorMessage = "Please select country Name")]
        public Currency fromCurrency { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Please select country Name")]
        public Currency toCurrency { get; set; }

        public double ConvertedCurrency { get; set; }
    }

这有助于您验证字段。

相关问题