Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reloading an ASP.NET MVC3 Partial View without using AJAX

I have an MVC3 application with Razor and I created a View that inside renders a Partial View. This is how the main View looks like:

@{Html.RenderPartial("_SearchFilters", Model.SearchFilters);}

@* Other HTML elements *@

Inside the _SearchFilters Partial View I have the following DropDownLists inside a Form element:

Choose Year
          @Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text"), DateTime.Now.Year)

Choose Month
          @Html.DropDownListFor(m => m.Month, new SelectList(Model.MonthsList, "Value", "Text"), Model.Month.ToString(), new { @disabled = "disabled" })


       <input type="submit" value="Display" />

I would like that upon Submit the two DropDownLists keep their status, namely the value selected by the user, when the View is reloaded with the filtered data.

Is there any way to do it without using AJAX?

UPDATE

The ViewModel is as follows:

public class TableSearchFiltersViewModel
{
    public bool YTM { get;  set; }

    public int? Month { get; set; }

    public int? Year { get; set; }

    public IEnumerable<SelectListItem> YearsList
    {
        get
        {
        return Enumerable.Range(2011, (DateTime.Now.Year - 2011 + 4)).Select(m => new SelectListItem
        {
            Value = m.ToString(),
            Text = m.ToString(),
        }).OrderBy(m => m.Value);
        }
    }

    public IEnumerable<SelectListItem> MonthsList
    {
        get
        {
           return Enumerable.Empty<SelectListItem>();
        }
    }

}

Thanks

Francesco

like image 318
CiccioMiami Avatar asked May 03 '11 09:05

CiccioMiami


2 Answers

When you submit the form to the corresponding controller action, this action should take as input parameter some view model. This view model's properties will be bound from the input fields contained in the form including the selected value of the two dropdowns. Then the controller action could return the same view which will preserve the selected values of the dropdown boxes.

I would recommend you to use Editor Templates though instead of rendering partials as this will ensure proper naming of the dropdowns and eventually preserve selected values:

@Html.EditorFor(x => x.SearchFilters)
like image 125
Darin Dimitrov Avatar answered Sep 24 '22 05:09

Darin Dimitrov


I don't have IDE at this time so couldn't test but this might work:

Choose Month

EDIT:

 @Html.DropDownListFor(m => m.Month, 
Model.MonthsList.Select(
        t => new SelectListItem {
                 Text = t.Name,
                 Value = t.Value,
                 Selected = t.Value == Model.Month,
        },

 Model.Month.ToString(), new { @disabled = "disabled" })
like image 22
ZeNo Avatar answered Sep 22 '22 05:09

ZeNo