2016-12-25 33 views
0

我在我的视图模型中有以下字段,我试图在自动完成中使用它,如果值不存在,则为表添加新值。使用IEnumerable值自动完成结果始终为空

永远传递给控制器​​的值始终是null

我认为这个问题是这里

“@ Html.TextBoxFor(米=> m.Genres,新的{@class = “形式控制”,@ ID = “术语”}) “

我需要获得。名称属性。我不想改变我的虚拟机。

public class LectureFormViewModel 
{ 
     public int Id { get; set; } 
     //Values 
     public byte Genre { get; set; } 
     public IEnumerable<Genre> Genres { get; set; } 
} 

public JsonResult GetGenresName(string term) 
{ 
    var genre = _context.Genres 
     .Where(gn => term == null || 
     gn.Name.ToLower().Contains(term.ToLower())).Select(x => new 
     { id = x.Id, value = x.Name }).Distinct().ToList(); 
    return Json(genre, JsonRequestBehavior.AllowGet); 
} 



@using (Html.BeginForm("Create", "VoosUp", FormMethod.Post, new {enctype = "multipart/form-data", id = "RestoForm"})) 
{ 
    //values 
    <div class="form-group"> 
     @Html.LabelFor(model => Model.Genre, new {@class = "control-label"}) 
     @Html.TextBoxFor(m => m.Genres, new {@class = "form-control", @id = "term"}) 
     @Html.ValidationMessageFor(m => m.Genres) 
    </div> 
    <input type="button" class="btn btn-primary btn-lg pull-right" onclick="GetLocation()" value="Finish"/> 
} 

@section scripts 
{ 
    @Scripts.Render("~/bundles/jqueryval") 

    <script> 
     $("#term").autocomplete({ 
      source: function(request, response) { 
       $.ajax({ 
        url: '@Url.Action("GetGenresName", "VoosUp")', 

        data: "{'GetGenresName': '" + request.term + "' }", 

        dataType: 'json', 
        type: "POST", 

        contentType: "application/json; charset=utf-8", 
        dataFilter: function(data) { return data; }, 
        success: function(data) { 
         console.log(term), 
          console.debug(); 
         response($.map(data, 
          function(item) { 
           return { 
            label: item.value, 
            value: item.value, 
            id: item.id 
           } 
          })); 
        } 
       }); 

      }, 
      minLength: 2 
     }); 
    </script> 
+0

@ M.kazemAkhgary yes真正的,但我的空值是在公共JsonResult GetGenresName(字符串术语)/ /空的问题在这里:@ Html.TextBoxFor(m => m.Genres它应该得到的名称值 –

回答

1

的问题是,你与IEnumerable<Genre>类型属性绑定的文本框,你的控制器动作需要string类型的参数,你应该用一个字符串类型属性映射文本框的值到控制器动作,另一件事是文本框的名字将被用于模型在后期绑定,你将有生成html文本框,如:

<input type="text" name="Genres" ................... /> 

但在控制器动作,您是参数名称term,这也将行不通,因为该值将发布在名为的参数中。

的解决方案是在文本框您的视图模型添加其他财产样结合:与术语财产

public class LectureFormViewModel 
{ 
     public int Id { get; set; } 
     public string Term {get;set;} 
     public byte Genre { get; set; } 
     public IEnumerable<Genre> Genres { get; set; } 
} 

现在,在您看来,绑定文本框:

@Html.TextBoxFor(m => m.Term, new {@class = "form-control"}) 

,并在控制器动作参数名称将为Term现在:

public JsonResult GetGenresName(string Term) 
{ 
}