如何在MVC Razor中使用Ajax创建单页搜索表单

时间:2019-01-29 15:40:15

标签: json asp.net-mvc razor

在MVC / Razor方面,我是一个初学者。基本上,我有2个页面仅用于显示与Json一起使用的API的搜索结果。

Index.cshtml :(只是一种形式)

@model ConsultaInterna.Models.SearchApi

<div class="jumbotron">
<h2>Consulta Interna</h2>
Placa
@using (Html.BeginForm("Search", "Home"))
{
    <input asp-for="Model.Name" class="form-control" name="name" id="txtName" />
    <input class="form-control" type="submit" id="ok" />
}

和Search.cshtml(也有表单。我现在只想离开此页面,现在我不能,因为如果直接从Search.cshtml加载它会给我类似

的错误

“解析值时遇到意外字符:<。路径”,第0行,位置0。”(显然是因为我正在尝试使用空搜索加载标签)

这是Search.cshtml

@model ConsultaInterna.Models.SearchApi

<div id="loader" class="spinner" style="display:none">OIE</div>

<div class="header formPesquisa">
@using (Ajax.BeginForm("Search", new AjaxOptions()
{
    HttpMethod = "POST",
    LoadingElementId = "loader",
    UpdateTargetId = "resultado"

}))
{
    <input placeholder="Placa" asp-for="Model.Name"  name="name" id="txtName" width="30" />

    <input class="pesquisa" type="submit" id="enviar" value="Ok" />
}

<div class="panel">Placa @Model.Name</div>
<div class="panel">Last Name / Model.LastName</div>

也很重要,Ajax表单无法正常运行...加载程序将不会显示。

1 个答案:

答案 0 :(得分:0)

  1. 您需要将loader div移至Ajax.BeginForm
  2. 您还需要添加resultado div以显示结果。

    @using (Ajax.BeginForm("Search", "Home", new AjaxOptions()
    {
        HttpMethod = "POST",
        LoadingElementId = "loader",
        UpdateTargetId = "resultado"
    
    }))
    {
        <div id="loader" class="spinner" style="display:none">OIE</div>
        <input placeholder="Placa" asp-for="Model.Placa" class="pesquisa placa" maxlength="7" name="placa" id="txtPlaca" width="30" />
        <input placeholder="CPF" asp-for="Model.CPF" class="pesquisa cpf" maxlength="11" name="cpf" id="txtCPF" />
        <input class="pesquisa" type="submit" id="enviar" value="Enviar" />
        <div id="resultado"></div>
    }
    
        <div class="panel">Placa @Model.Name</div>
        <div class="panel">Last Name / Model.LastName</div>
    </div>
    

您还需要确保已将相关的引用添加到特定的兼容ajax库。例如:

BundleConfig

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
  "~/Scripts/jquery.unobtrusive-ajax.min.js",
  "~/Scripts/jquery.validate*"));

_layout.cshtml

@Scripts.Render("~/bundles/jqueryval")

控制器操作示例

[HttpPost]
public ActionResult Search(string placa, string cpf)
{
    return new JsonResult { Data = "found", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Image showing ajax returned