View is not refreshing when the model is changed in ASP.NET MVC

108 views Asked by At

My problem is when i try to refresh view with changed model after a post in ASP.NET MVC. I read a lot about the problem and realized that this happened because of html helpers and model binding. Also almost everyone's solution to this problem is to use ModelState.Clear(), but in my case that doesn't help. Any help would be appreciated.

public class StudentPreferences
{
    public String ProgrammeName { get; set; }
    public int PrefNumber { get; set; }
    public String Faculty { get; set; }
}

public class StudentPreferencesController : Controller
{
    private Dictionary<String, List<String>> programmes = new Dictionary<String, List<String>>();
    private List<StudentPreferences> model = new List<StudentPreferences>();

    public StudentPreferencesController()
    {
        List<String> p1 = new List<String>();
        p1.Add("KN");
        p1.Add("Info");
        p1.Add("IS");

        List<String> p2 = new List<String>();
        p2.Add("ikonomika");
        p2.Add("Selsko stopanstvo");

        List<String> p3 = new List<String>();
        p3.Add("Biologiq");
        p3.Add("Biotehnologii");
        p3.Add("Molekulqrna");

        List<String> faculties = new List<String>();
        faculties.Add("FMI");
        faculties.Add("Stopanski");
        faculties.Add("Bilogicheski");

        programmes.Add(faculties[0], p1);
        programmes.Add(faculties[1], p2);
        programmes.Add(faculties[2], p3);

    }

    public JsonResult GetProgrammes(string faculty)
    {
        if (faculty != "Please Select")
            return Json(programmes[faculty]);
        else
            return Json(new List<String>());
    }

    [HttpGet]
    public ActionResult Index()
    {
        String user = User.Identity.Name;
        user = "Evgeny";
        ViewData["userName"] = user;

        List<String> l = programmes.Keys.ToList<string>();
        l.Insert(0,"Please Select");
        SelectList faculties = new SelectList(l);

        ViewData["faculties"] = faculties;

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(String faculty, String programmeName)
    {
        String user = User.Identity.Name;
        user = "Evgeny";
        ViewData["userName"] = user;

        List<String> l = programmes.Keys.ToList<string>();
        l.Insert(0, "Please Select");
        SelectList faculties = new SelectList(l);

        ViewData["faculties"] = faculties;

        StudentPreferences pref = new StudentPreferences { Faculty = "FMI", ProgrammeName = "KN", PrefNumber = 1 };
        model.Add(pref);
        ModelState.Clear();
        return View("Index",model);
    }
}

This is my Index view.

@model IEnumerable<StudentRanking.Models.StudentPreferences>
@{
    ViewBag.Title = "StudentPreferences";
}

@section Scripts
{
<script type="text/javascript">
    $(document).ready(function () {
        $("#programmeName").prop("disabled", true);
        $("#faculty").change(function () {
            if ($("#faculty").val() != "Please select") {
                var options = {};
                options.url = "/StudentPreferences/getprogrammes";
                options.type = "POST";
                options.data = JSON.stringify({ faculty: $("#faculty").val() });
                options.dataType = "json";
                //<a href="~/Views/ProgrammeRules/Index.cshtml">~/Views/ProgrammeRules/Index.cshtml</a>
                options.contentType = "application/json";
                options.success = function (states) {
                    $("#programmeName").empty();
                    for (var i = 0; i < states.length; i++) {
                        $("#programmeName").append("<option>" + states[i] + "</option>");
                    }
                    $("#programmeName").prop("disabled", false);
                };
                options.error = function () { alert("Error retrieving states!"); };
                $.ajax(options);
            }
            else {
                $("#programmeName").empty();
                $("#programmeName").prop("disabled", true);
            }
        });
    });

    function SubmitClick() {
        $.ajax({
            type: 'POST',
            url: "/StudentPreferences/index",
            data: {
                faculty: $("#faculty option:selected").text(),
                programmeName: $("#programmeName option:selected").text()
            }

        });
    };

</script>
}

<h2>@ViewData["userName"]</h2>
<h2>Подаване на желания</h2>
<div>Изберете факултет</div>
@Html.DropDownList("faculty", ViewData["faculties"] as SelectList, new { @id = "faculty" })
<select id="programmeName"></select>
<input type="submit" value="Submit" onclick="javascript:SubmitClick()"  />
<table>
<tr>
    <th><label>Номер на желание</label></th>
    <th><label>Факултет</label></th>
    <th><label>Специалност</label></th>
    <th></th>
</tr>
@if (Model != null)
{
    foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.PrefNumber)</td>
            <td>@Html.DisplayFor(modelItem => item.Faculty)</td>
            <th>@Html.DisplayFor(model => item.ProgrammeName)</th>
        </tr>
    }
}
</table>
0

There are 0 answers