MVC 4局部视图导致页面在提交时无响应

时间:2014-09-10 17:04:52

标签: c# javascript jquery asp.net-mvc asp.net-mvc-4

情况:在我的C#/ MVC 4解决方案中,我正在使用一个带有局部视图的视图。视图是一个带有提交按钮的表单。部分视图使用隐藏的div,但如果选中该复选框,则可以显示。

问题:如果隐藏了部分视图,则提交正常。如果未隐藏部分视图,则提交会导致页面无响应,如果等待3分钟左右,则提交最终会按预期工作。

代码如下。提前感谢您的考虑。我是一名新手开发者,因此欢迎所有评论,建议和批评。

代码:

模型

namespace MyModels
{
   public class MainModel
   {
       public SelectListItem Things { get; set;}

       public IEnumerable<OtherModel> MoreThings { get; set;}
   }
}

查看     //名为MyView     @model MyModels.MainModel     @using MyModels     @if(Model!= null){

    using (Html.BeginForm("MyViewName", "MyControllerName", FormMethod.Post, new { id = "view-form" }))
{
    @Html.LabelFor(model => model.things)
    @Html.DropDownList("", (Selectist)ViewBag.things)
    @Html.ValidationMessageFor(model => model.field1)

    @Html.CheckBoxWithLabel("aNameAttribute", Model.valueAttribute.ToString(), "anIdAttribute", Model.valueAtttribue ==1, "aLabel", "a_Toggle_Class") 
    <div class="treeview" style="display: none;">
    <fieldset>
        <legend>Title</legend>
    //view causing issues replaces the div below
    <div id="replacedDiv"></div>
    </fieldset>
    </div>

    <p>
        <input type="submit" value="Submit" />
    </p>
}

}

<script type="text/javascript">
    $(document).ready(function () {
       $.ajax({
           url: "/MyController/MyPartialView",
           contentType: "application/html; charset=utf-8",
           cache: "false",
           type: "GET",
           datatype: "html"
       })
       .success(function (result) {
           $('#replacedDiv").html(result);
       })
   });
</script>

部分视图

//named _MyPartialView
@model MyModels.MainModel
@using MyModels

@foreach (var moreThings in ViewBag.moreThings)
{
    <div id="replacedDiv">
    <label>
    <input type="checkbox" id=@moreThings.id value=@moreThings.name />@moreThings.name </label>
    </div>
}

控制器

namespace Main.Controllers
{
    public class MyController
    {
       [HttpGet]
       public ActionResult Index(MainModel model)
       {
          return View(model);
       }

       public ActionResult MyView()
       {
           var model = new MainModel();

           return View(model);

       }

       public ActionResult MyPartialView(MainModel model)
       {
           <OtherModel> moreThings = BLotherModel.GetMoreThings();
           ViewBag.moreThings = moreThings;

           return PartialView("_MyPartialView", promotion);
       }

       [HttpPost]
       public ActionResult MyView(FormCollection collection)
       {
          MainModel model = new MainModel();

          return SaveModel(model);
       }
    }
}

1 个答案:

答案 0 :(得分:2)

在你正在使用的ajax中:

$('#replacedDiv").html(result);

但您的部分视图包含在循环中生成的<div id="replacedDiv">

用以下内容替换部分视图代码:

@foreach (var moreThings in ViewBag.moreThings)
{
    <label>@moreThings.name </label>
    <input type="checkbox" id=@moreThings.id value=@moreThings.name />
}

它应该没问题