Simple Ajax in asp.net MVC 3, update the model and rerender part

后端 未结 1 1401
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-06 17:33

I come from a more WPF application background and I\'m used to bindings and such. Jumping into websites then can come with it\'s problems as they work so much more

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 18:11

    Here's a full example.

    Model:

    public class MyViewModel
    {
        public int Year { get; set; }
        public IEnumerable Years
        {
            get
            {
                return Enumerable.Range(1980, 40).Select(x => new SelectListItem
                {
                    Value = x.ToString(),
                    Text = x.ToString()
                });
            }
        }
    
        public IList Data { get; set; }
    }
    
    public class TheData
    {
        public int Year { get; set; }
        public string Foo { get; set; }
        public string Bar { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyViewModel();
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(int year)
        {
            var model = new[]
            {
                new TheData { Year = year, Foo = "foo 1", Bar = "bar 1" },
                new TheData { Year = year, Foo = "foo 2", Bar = "bar 2" },
                new TheData { Year = year, Foo = "foo 3", Bar = "bar 3" },
            };
            return PartialView("_data", model);
        }
    }
    

    Index.cshtml view:

    @model MyViewModel
    
    
    
    
    @using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "data" }))
    {
        @Html.DropDownListFor(x => x.Year, Model.Years, new { id = "yearsddl" })
    }
    
    
            @Html.Partial("_data", Model.Data ?? Enumerable.Empty())
        
    Year Foo Bar

    The jquery.unobtrusive-ajax.js script inclusion should be moved out of the index view inside the layout for example and the custom js that subscribes for the change event of the dropdownlist should be moved into a separate js file and included from the Layout. I just put them here to illustrate a full example of what's required for the view to work.

    _Data.cshtml partial:

    @model IList
    
    @for (int i = 0; i < Model.Count; i++)
    {
        
            @Html.DisplayFor(x => x[i].Year)
            @Html.DisplayFor(x => x[i].Foo)
            @Html.DisplayFor(x => x[i].Bar)
        
    }
    

    0 讨论(0)
提交回复
热议问题