weixin_33725239 2011-04-20 12:15 采纳率: 0%
浏览 27

如何在MVC 3中使用Ajax?

I have a form that I'd like to submit through Ajax. This form is stored in a partial view - so the entire partial view represents a single form.

I generate ten of these forms with a foreach loop:

 @foreach (Product p in Model.Products)
 {                     
    @Html.Partial("_EditProduct", p)                    
 }

This works fine.

In the _EditProduct partial view I have:

@using (Ajax.BeginForm("Update", "Product", new AjaxOptions { UpdateTargetId = "updateStatus" })) {
     <span id="updateStatus">Update will go here</span> }

     // Product fields

        <div>                
             <input type="submit" value="Update" class="btn"/>
        </div>
    }

Clicking on a submit button posts to a controller:

[HttpPost]
public JsonResult Update(int id, FormCollection collection)
{
   ProductService pService = new ProductService();
   Product p =pService.Find(id);

   UpdateModel(p);
   return Json(p);            
}

This updates the product, but return crashes due to serialization error.

The main problem is that I struggle to find a good resource on MVC 3, especially the Ajax part. Tutorials and blogs seem to do everything in a very different way. Ideally I'd like to use as much of .NET and MVC 3 functionality as possible, rather than writing loads of jQuery/JavaScript.

Thank you

Edit: Just to add, I'd like to stay far away from MS Ajax Control Toolkit

  • 写回答

3条回答 默认 最新

  • ?Briella 2011-04-20 12:27
    关注

    MVC has always had Ajax helpers since its first release. These allow you to generate “ajax-enabled” html elements.However, in ASP.NET MVC 3 these helpers have been significantly improved. They no longer rely on the MS-Ajax client libraries to do their work – instead they use jQuery and the unobtrusive jQuery extensions that ship with MVC3. They also use HTML5 data- attributes to annotate a particular element with metadata rather than defining inline scripts.

    The above example now generates the following markup with MVC3:

    code

    So, have jQuery and the jQuery.unobtrusive-ajax scripts included and use javascript to submit the form if it’s enabled.

    Also have a look at http://dotmac.rationalmind.net/2011/03/basic-ajax-with-mvc3-razor/

    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题