English 中文(简体)
MVC Ajax 表单返回视图的全部内容
原标题:MVC Ajax Form returning entire contents of View

我正在使用 MVC4。 在我的项目中启用并引用了无侵扰 JavaScript 。 Ajax 脚本正在装入我的共享主页。 FireBug 没有报告错误或404 s 。

我在我的页面中添加了一个 < code> Text 框, 更新了我 < code> Ajax 窗体内 < code > Ajax 字段的内容。 当用户按键和 < code> KeyUp 事件火灾时, 我用电话强制我的 < code> Ajax 表格提交 :

$("form#ajaxForm").trigger("submit");

ajaxForm 是 Ajax 表格的名称。 这很好。 表格在幕后提交, 我的控制器事件火灾。 根据用户输入的新数据更新模型 。

然而,奇怪的是,当结果返回到我的窗体时。我的窗体 < code> div 标记的全部内容被结果 -- -- 即整个页面 -- -- 所取代。

<div id="basic-modal-content"">
   <input id="breed" type="text"/>
<div>
<form id="ajaxForm" method="post" data-ajax-update="#results" data-ajax-mode="replace" data-ajax="true" action="/Poultry/ListBreeds?Length=7">
   <div id="results">
    ->THIS AREA IS GETTING REPLACED WITH THE ENTIRE FORM <-
      <div id="basic-modal-content">
      </div>
   </div>
</form>
  • Notice how basic-modal-content now contains itself, another basic-modal-content. The result div should only contain the updates results, not the entire view -- obviously.

我的代码如下:

<强度 > 查看 ( BreedSextorPartial.cshtml )

@model IQueryable<Inert.BreedViewModel>

<script type="text/javascript">
    $(document).ready(function () {
        $("#breed").keyup(function (e) {
            $("input[name=breedSearch]").val($("#breed").val());
            $("form#ajaxForm").trigger("submit");
        });
    });
</script>

<div id="basic-modal-content">
<input id="breed" type="text" style="width:100%; height:22px;" />
    <div>
        <div style="margin-top: 4px;">
            <label for="breed">Begin by typing a breed, e.g. <span style="font-style: italic">Wyandotte</span></label>
        </div>
    </div>
    @using (Ajax.BeginForm("ListBreeds", "Poultry", new AjaxOptions {UpdateTargetId = "results" }, new { id = "ajaxForm" }))
    {
        <input id="breedSearch" name="breedSearch" type="hidden" />
    }
    <div id="results" style="height: 320px; color: black; margin-top: 12px; font-size: 18px;">
        @{
            var grid = new WebGrid(Model, ajaxUpdateContainerId: "results");
            int c = Model.Count();
         }
        @grid.GetHtml(tableStyle: "webgrid",
            alternatingRowStyle: "webgrid-alternating-row",
            rowStyle: "webgrid-row-style",
            displayHeader: true)
    </div>
</div>
<script type="text/javascript" src="/scripts/jquery.simplemodal.js"></script>
<script type="text/javascript" src="/scripts/basic.js"></script>

<强 > 主计长 ( 禽类主计长.cs )

[HttpPost]
public ActionResult ListBreeds(string breedSearch)
{
    InertDatabaseEntitiesConnection db = new InertDatabaseEntitiesConnection();
    var breeds = db.Breeds.Where(q => q.Name.Contains(breedSearch));
    var names = breeds.Select(q => new BreedViewModel { Name = q.Name });
    return PartialView("BreedSelectorPartial", names);
}

我不知道我到底哪里搞错了 我花了好几个小时才弄清楚,有办法吗?

最佳回答

第一个问题是,您使用 Ajax. beginForm 帮助器的超载错误(但不会造成不受欢迎的行为,这只是一个副注):

@using (Ajax.BeginForm(
    "ListBreeds",                                      // actionName
    "Poultry",                                         // routeValues
    new AjaxOptions { UpdateTargetId = "results" },    // ajaxOptions
    new { id = "ajaxForm" })                           // htmlAttributes
)

您需要:

@using (Ajax.BeginForm(
    "ListBreeds",                                      // actionName
    "Poultry",                                         // controllerName
    null,                                              // routeValues
    new AjaxOptions { UpdateTargetId = "results" },    // ajaxOptions
    new { id = "ajaxForm" })                           // htmlAttributes
)

真正的问题在于,您需要将 div 置于 的外部部分和主视图中 :

<div id="results" style="height: 320px; color: black; margin-top: 12px; font-size: 18px;">
    @Html.Partial("BreedSelectorPartial")
</div>

当然,如果只需更新 WebGrid 部分,那么只将网格留在部分内并在主视图中将窗体移到外边就更有意义了。

所以,你现在的主要观点是:

@model IQueryable<BreedViewModel>
<script type="text/javascript">
    $(document).ready(function () {
        $("#breed").keyup(function (e) {
            $("input[name=breedSearch]").val($("#breed").val());
            $("form#ajaxForm").trigger("submit");
        });
    });
</script>

<div id="basic-modal-content">
    <input id="breed" type="text" style="width:100%; height:22px;" />
    <div>
        <div style="margin-top: 4px;">
            <label for="breed">Begin by typing a breed, e.g. <span style="font-style: italic">Wyandotte</span></label>
        </div>
    </div>
    @using (Ajax.BeginForm("ListBreeds", "Poultry", null, new AjaxOptions { UpdateTargetId = "results" }, new { id = "ajaxForm" }))
    {
        <input id="breedSearch" name="breedSearch" type="hidden" />
    }
    <div id="results" style="height: 320px; color: black; margin-top: 12px; font-size: 18px;">
        @Html.Partial("BreedSelectorPartial")
    </div>
</div>

唯一需要更新的部分是 BreedSectorPartial.cshtml 部分,其中含有网格:

@model IQueryable<BreedViewModel>
@{
    var grid = new WebGrid(Model, ajaxUpdateContainerId: "results");
}
@grid.GetHtml(
    tableStyle: "webgrid",
    alternatingRowStyle: "webgrid-alternating-row",
    rowStyle: "webgrid-row-style",
    displayHeader: true
)
问题回答

前几天我也有类似的东西

我记不清到底有什么问题, 但它与返回整个对象有关, 而不仅仅是该对象的 HTML 元素。

我目前找不到代码, 但如果你正在使用 Firebug 或类似的东西, 看看你能不能在返回的数据上放个监视器, 如果我正确的话, 我只需要在行的结尾添加.html 。

抱歉有点模糊 但希望能帮你一点

Are you sure you are not doing the regular form submit ? I think this line $("form#ajaxForm").trigger("submit"); is doing the regular form submit. You should probably do an ajax form post here instead of invoking the normal form submit. You are seeing the entire page reload because of that.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...