Razor Mvc 3 + Jquery自动完成问题

时间:2016-06-23 16:04:27

标签: jquery asp.net-mvc razor autocomplete

Helllo所有人,

我试图用Razor mvc3编写一个简单的注册表单,使用jquery自动完成来填充数据库中的城市,状态信息。剃刀视图使用表单验证,jquery填充文本框信息。但是,将数据从所述文本框传递到控制器时,值始终为null。

视图中的文本框:

<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"})

Controller(registration.city始终为null):

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");
            }
        }

2 个答案:

答案 0 :(得分:2)

而不是使用此

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

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

UIViewControllers

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

答案 1 :(得分:-1)

经过相当多的搜索后,我想出了一个解决方案

查看:

 <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();
}