【问题标题】:I want to set default value that is missing when click on the dropdown list.I would like to be unable to select "Please select" value我想设置单击下拉列表时缺少的默认值。我希望无法选择“请选择”值
【发布时间】:2019-03-11 05:55:48
【问题描述】:

我想设置单击下拉列表时会丢失的默认值。我希望无法选择“请选择”值。当我单击 materialId 或 depotId 中的“请选择”值时,“”空值由 ajax 发送,我收到错误。我怎样才能防止这种情况发生?

创建.cshtml

  <div class="form-group">
        @Html.LabelFor(model => model.materialId, "Material names", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("materialId", null, "Please select", htmlAttributes: new { @class = "form-control chosen" })
            @Html.ValidationMessageFor(model => model.materialId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.depotId, "Product Outlet", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("depotId", null, "Please select", htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.depotId, "", new { @class = "text-danger" })
        </div>
    </div>
    <script type="text/javascript">
            $(document).ready(function () {
                $('#depotId').change(function () { sendDataByAjax(); });
                $('#materialId').change(function () { sendDataByAjax(); });
        })
    function sendDataByAjax() {
        var materialId= $('#materialId option:selected').val();
        var depotId= $('#depotId option:selected').val();

        if (materialId == "" || depotId == "") {
          // I can not write this
        }
        $.ajax({
            type: "GET",
            url: "@Url.Action("GetStock", "OutgoingProduct")",
            data: {
                'materialId': materialId,
                'depotId': depotId
            },
            success: function (data) {
                $("#stock").html(data);
                }
        });
        }
    </script>
}

当“”转到我的控制器时,我在这里遇到错误。因为它不是int。

OutgoingProductController.cs

public string GetStock(string materialId, string depotId)
{
    int did = int.Parse(depotId);
    int mid = int.Parse(materialId);

【问题讨论】:

  • 当占位符文本项被选中时,materialIddepotId 的值是多少?他们是否被分配了undefined(使用console.log() 来查看他们)?
  • 当我从列表中选择时,我从 materialId 和 depotId 中获取数字,例如“1050”、“3”。但是当我选择“请选择”值时,我得到的是空值。
  • 你为什么不改变你的if条件来检查null而不是""
  • @büşratabak,那么当您选择“请选择”时,您期望哪些值会返回?
  • 当然,我尝试了 null 而不是 ""。不工作

标签: c# html asp.net asp.net-mvc


【解决方案1】:

由于您的下拉列表中选择的值是作为数值传递的,您可以使用parseInt() 函数尝试从客户端解析数值,然后检查NaN,如果该值是数字则触发 AJAX 回调:

function sendDataByAjax() {
    var materialId = parseInt($('#materialId option:selected').val());
    var depotId = parseInt($('#depotId option:selected').val());

    if (isNaN(materialId) || isNaN(depotId)) {
        // do something, e.g. alert user
        return false;
    }
    else {
        $.ajax({
            type: "GET",
            url: "@Url.Action("GetStock", "OutgoingProduct")",
            data: {
                'materialId': materialId,
                'depotId': depotId
            },
            success: function (data) {
                $("#stock").html(data);
            }
        });
    }
}

然后确保您的操作方法包含int 类型的两个参数,因此无需使用int.Parse(),如果解析的字符串为空值,则会抛出异常:

public ActionResult GetStock(int materialId, int depotId)
{
    int did = depotId;
    int mid = materialId;

    // other stuff
}

【讨论】:

    【解决方案2】:

    尝试在materialId == "" || depotId == "" 时返回false

    function sendDataByAjax() {
            var materialId= $('#materialId option:selected').val();
            var depotId= $('#depotId option:selected').val();
    
            if (materialId == "" || depotId == "") {
              return false;
            }
            $.ajax({
                type: "GET",
                url: "@Url.Action("GetStock", "OutgoingProduct")",
                data: {
                    'materialId': materialId,
                    'depotId': depotId
                },
                success: function (data) {
                    $("#stock").html(data);
                    }
            });
    }
    

    【讨论】:

      【解决方案3】:

      解决此问题的方法不是您尝试的方法。这样做的方法应该是使用验证系统,可用于 MVC。

      更改您的 get 方法以使用模型,例如:

      public class StockRequestModel
      {
          [Required]    
          public int materialId { get; set }
      
          [Required]
          public int depoId { get;set; }
      }
      

      你的控制器方法可以变成这样:

      public string GetStock([FromUri] StockRequestModel model)
      {
          if ( !ModelState.IsValid )
          {
               some code here
          } 
      
          //at this point your model is valid and you have IDs so can proceed with your code
      }
      

      通常,在 MVC 中,您会在结果中返回带有状态的原始视图,这样您就可以触发前端验证。在您的情况下,您似乎在 MVC 应用程序中有一个 WebAPI 控制器,但您仍然可以使用前端验证。

      还有其他与你相关的问题,比如Client side validation with Angularjs and Server side validation with Asp.net MVC

      通常我会投票关闭它作为重复,但在这种情况下,我认为值得指出问题和解决方案。

      另一个可以去的地方是https://angularjs.org/,然后检查表单验证部分以获得纯前端验证。当然,您希望同时保留前端和后端验证。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-13
        • 2020-04-03
        • 1970-01-01
        • 2019-06-27
        • 1970-01-01
        • 1970-01-01
        • 2022-01-17
        • 2017-12-08
        相关资源
        最近更新 更多