【问题标题】:Razor Mvc 3 + Jquery autocomplete issueRazor Mvc 3 + Jquery 自动完成问题
【发布时间】:2016-10-26 02:02:23
【问题描述】:

大家好,

我正在尝试使用 Razor mvc3 编写一个简单的注册表单,使用 jquery 自动完成功能从数据库中填充城市、州信息。 razor 视图使用表单验证,jquery 填充文本框信息。但是,当将数据从所述文本框传递到控制器时,值始终为空。

视图中的文本框:

<input data-autocomplete="@Url.Action("AutoCompleteCity", "Search")"  class="form-control" placeholder="Enter City" name="city" id="city" />  

我也尝试过这种替代方法,但无济于事:

@Html.TextBoxFor(u => u.city, new { @class="form-control", @placeholder="Enter city"})

控制器(registration.city 始终为空):

if (registration.city == null) ModelState.AddModelError("", "Must select City.");

Jquery 自动完成:

$("#city").
        autocomplete({
        source: function (request, response) {
            $.ajax({    
                url: serviceURL,
                type: "POST",
                dataType: "json",
                data: { term: request.term },
                success: function (data) {
                    $("#targetDiv").append($("<ul id='targetUL' class='list-group'></ul>"));
                    //Removing previously added li elements to the list.
                    $("#targetUL").find("li").empty();

                    $.each(data, function (i, value) {
                        //On click of li element we are calling a method.                        
                        $("#targetUL").append($("<li class='list-group-item' onclick='javascript:addText(this)'>" + value.city + ", " + value.state + "</li>"));
                    });
                }
            })
        },

任何帮助将不胜感激。我对 Razor 有点陌生,所以我可能一定遗漏了一些东西。谢谢!!

编辑 - 控制器代码:

 [HttpPost]
        public ActionResult register(Models.UserForm registration)
        {                
            if (registration.email != null && registration.email.Length > Constants.MAX_MAIL_SIZE) ModelState.AddModelError("longUsername", "Username is too long");
            if (registration.email != null && !registration.email.Contains('@')) ModelState.AddModelError("wrongEmail", "Email is not valid.");
            if (registration.email == null || registration.email.Trim().Length == 0) ModelState.AddModelError("", "Name cannot be blank.");

            if (registration.password != null && registration.password.Length > Constants.MAX_PASS_SIZE) ModelState.AddModelError("", "Password is too long.");
            if (registration.password == null || registracion.contrasenia.Trim().Length == 0) ModelState.AddModelError("", "Password cannot be blank.");

            if (registration.name != null && registration.name.Length > Constantes.MAX_NOMBRE_SIZE) ModelState.AddModelError("", "Name is too long.");
            if (registration.name == null || registration.name.Trim().Length == 0) ModelState.AddModelError("", "Name cannot be blank.");

            if (registration.city == null) ModelState.AddModelError("", "Must Select City.");
            if (!db.validateExistingUser(registration.email)) ModelState.AddModelError("", "User already exists.");
            if (!ModelState.IsValid)
            {
                return View();
            }
            else
            {
                Usuario u = db.registerUser(registracion);
                Session["User"] = u;
                return View("Index");
            }
        }

【问题讨论】:

    标签: jquery asp.net-mvc razor autocomplete


    【解决方案1】:

    而不是使用这个

    data-autocomplete="@Url.Action("AutoCompleteCity", "Search")"
    

    尝试将元素包装在表单中,然后在表单中设置隐藏字段

    <input type="hidden" value="" />
    

    然后在 JQuery 中设置值并与其余字段一起提交

    【讨论】:

    • Jquery 自动完成确实返回了值,当我将数据发布到控制器时出现空错误
    • 对我编辑的困惑我的答案很抱歉这个帮助?
    • 也试过了,但仍然没有数据到达控制器
    • 你能用控制器中的代码更新问题吗:)
    • 我刚刚包含了控制器代码。必须翻译变量以使其更具可读性。谢谢
    【解决方案2】:

    经过一番搜索,我想出了一个解决方案

    查看:

     <div class="editor-field">
    
          @Html.TextBoxFor(u => u.city.city, new { @class="form-control", @placeholder="Enter Your City"})
          <div id="targetDiv">                                 
          </div>                                
         @Html.HiddenFor(u => u.city.cityId)
         @Html.HiddenFor(u => u.city.state, new { Value = "" })                                       
         <br />
     </div>
    

    使用 razor 语法在隐藏输入中传递我需要的 ID(感谢 @ben-jones 的建议)。

    我还对 Jquery Ajax 方法做了一些调整,利用 data-* Attributes

    $("#city_city").
            autocomplete({
            source: function (request, response) {
                $.ajax({    
                    url: serviceURL,
                    type: "POST",
                    dataType: "json",
                    async: false,
                    data: { term: request.term },
                    success: function (data) {
                        $("#targetDiv").append($("<ul id='targetUL' class='list-group'></ul>"));
                        //Removing previously added li elements to the list.
                        $("#targetUL").find("li").empty();
    
                        $.each(data, function (i, value) {
                            //On click of li element we are calling a method.                        
                            $("#targetUL").append($("<li class='list-group-item' onclick='javascript:addText(this)' value='" + value.cityId+ "' data-city='" + value.city+ "' data-state='" + value.state+ "' >" + value.city+ ", " + value.state+ "</li>"));
                        });
                    }
                })
            },
            minLength: 3,
            delay: 200,
            messages: {
                noResults: "", results: ""
            }
            }).keyup(function (e) {
    
                $("#targetUL").empty();
    
                $("#city_city").autocomplete().term = null;            
            });
    
    });
    
    
    function addText(e) {
        var text= e.innerText;   
    
        $("#city_city").removeClass("input-validation-error");
        //setting the value attribute of textbox with selected li element.
        $("#city_city").html(text);
        $("#city_city").val(text);
    
        $("#city_cityIdidLocalidad").val(e.value);
        $("#city_city").val(e.getAttribute("data-city"));
        $("#city_state").val(e.getAttribute("data-state"));
    
    
        //Removing the ul element once selected element is set to textbox.
        $("#targetUL").empty();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 2010-12-04
      • 2011-08-08
      • 2013-01-22
      • 2016-05-31
      • 2011-10-08
      相关资源
      最近更新 更多