2

I am very new to MVC and have just come across a scenario that I need some help with.I am creating a website in ASP.NET, C#.NET Using MVC 4. So as per my requirement I have two DropDowns which is <select> tag in my cshtml page.

1) selectUniversity
2) selectCollege

I have a Database table named as College_table, whose fields are:

1) Univ_ID
2) Univ_Name
3) College_ID
4) College_Name
5) College_Address
6) College_Contact

Now on my selectUniversity I have a listed all the Universities name and in selectCollege all the college names belongs to the university selected in selectUniversity drop down. And the WebGrid content will change based on the selection of any of the above dropdown.

My code changes: VIEW Javascript:

<script type="text/javascript">
      function ajaxCallGetColleges() {
             var e = document.getElementById("selectUniversity");
             var strUniv = e.options[e.selectedIndex].value;
             $.ajax({
                  url: '@Url.Action("GetCollegesActionResult", "CollegeController")',
                  type: 'POST',
                  data: { 'data': strUniv },
                  success: function (ResponceObject) {
                       alert(ResponceObject);//Need to update this data into WebGrid and selectCollege dropdown.
                  }
             });
      }
      function ajaxCallGetCollegeDetail() {
             var e = document.getElementById("selectCollege");
             var strCollege = e.options[e.selectedIndex].value;
             $.ajax({
                  url: '@Url.Action("GetCollegeDetailActionResult", "CollegeController")',
                  type: 'POST',
                  data: { 'data': strCollege },
                  success: function (ResponceObject) {
                       alert(ResponceObject);//Need to update this data into WebGrid.
                  }
             });
      }
</script>

CSHTML Code:

<table>

        <tr>
            <td>
                <select id="selectUniversity" name="selectUniversity" onchange="ajaxCallGetColleges()">
                    @{
                        //Logic for adding University names as options to the dropdown dynamically
                     }
                </select>
            </td>

            <td>
                <select id="searchBy" name="searchBy" onchange="ajaxCall()">
                   <select id="selectUniversity" name="selectUniversity" onchange="ajaxCallGetCollegeDetail()">
                    @{
                        //Logic for adding college names as options to the dropdown dynamically
                     }
                </select>
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <div id="MyGrid">
                    @{
                        WebGrid grid = new WebGrid(source: Model,
                                       defaultSort: "Name",
                                       rowsPerPage: 15);
                        grid.SortDirection = SortDirection.Ascending;
                    }

                    @grid.GetHtml(
    fillEmptyRows: false,
    mode: WebGridPagerModes.All,
    firstText: "<< First",
    previousText: "< Prev",
    nextText: "Next >",
    lastText: "Last >>",
     columns: new[] {
        grid.Column("Univ_ID",header: "Univ ID", canSort: false),
        grid.Column("Univ_Name",header: "Univ Name"),
        grid.Column("College_ID",header: "College ID", canSort: true),
        grid.Column("College_Name",header: "College Name"),
        grid.Column("College_Address", header: "College Address", canSort: true),
        grid.Column("College_Contact",header: "Contact"),
        grid.Column("", header:"Edit", format: (item) => Html.ActionLink("Edit", "Edit", new { univ_ID=item.Univ_ID })),
        grid.Column("", header:"Delete", format: (item) => Html.ActionLink("Delete", "Delete", new { univ_ID=item.Univ_ID}, new { onclick="return confirm('Are you sure?');"}))
    })
                </div>
            </td>
        </tr>
    </table>

CONTROLLER C#.NET Code:

public ActionResult SearchByBranchStatus(string data)
        {

            List<CollegesDetail> colleges= _collegeService.GetCollegesDetail();

            var RespObject = colleges.Where(c => c.Name == data);
            return View(RespObject);
        }
 public ActionResult GetCollegeDetailActionResult(string data)
        {
            List<CollegeDetail> colleges= _collegeService.GetCollegeDetail();

            var RespObject = colleges.Where(c => c.Name == data);
            return View(RespObject);
        }

I have gone through many SO as well as MSDN sites also but I did not find any help. Please provide me any reference or idea to achieve this problem. I know relate to my question there are many questions asked in many forums but I have not got them. May be its very simplest one but as I recently started working on MVC 4 I don't have good hands on MVC 4. I am eagerly waiting for the answer. Any help would really be appreciated. Thanks in advance..

Note:- Currently I am referring MSDN Magazine

UPDATE:- I have answered partially to my question for how to update WebGrid on DropDown selection change through Ajax in MVC 4

SharpUrBrain
  • 3,180
  • 5
  • 38
  • 56
  • Instead of returning to a view, you should return json from your controller. Also you are requesting a POST type from $.ajax but you have not declared you controller actions are [HttpPost]. check this [post](http://stackoverflow.com/questions/15719399/mvc-4-cascading-dropdown-lists-issue-with-ajax-javascript-call) – Karthik Chintala Apr 01 '13 at 09:22
  • Without [HttpPost] also its giving me data in case of return Content(string), but in case of return View() its giving error to my Ajax call – SharpUrBrain Apr 01 '13 at 10:01
  • if you return as view, it doesnot return in the formats that $.ajax call expects thats why it produces error. When you return the Content it returns as string and ajax call is intelligent to detect the type as string and it falls to success call back – Karthik Chintala Apr 01 '13 at 10:32
  • Try returning like this: `return Json(respObject, JsonRequestBehaviour.AllowGet);` place a `debugger;` in the success callback and see what are all the options avaliable in the returned data – Karthik Chintala Apr 01 '13 at 10:33
  • I am getting the Model as response Object now, but how will I update/ bind WebGrid now? – SharpUrBrain Apr 01 '13 at 11:04
  • loop through the every element in the responce using a for loop. you should declare an id for you webgrid and you need to find the necessary element that you need to update/modify using jquery functions like `.closest('tr')` `find('table')` etc and finally add the data by finding the element – Karthik Chintala Apr 01 '13 at 11:30
  • But my responseObject is in Json format and I need Model Object to allocate as source to the WebGrid. In this case how will I assign the responseObject to my WebGrid? – SharpUrBrain Apr 01 '13 at 12:54
  • I dont have an idea of how to acheive that – Karthik Chintala Apr 01 '13 at 13:29

1 Answers1

3

Finlay I have resolved this issue by using Partial view. Now I fill its very simple. Steps how I achieved is mentioned below:

  1. I have created two views(MainView and _MainView)
  2. _MainView is a partial view where I put the complete WebGrid and that WebGrid I have binded with Model.
  3. Now in the MainView I placed the partialview(_MainView) into a div tag and called the partial view with Model(@Html.Partial("_MainView", Model))
  4. In Ajax call I made the call to the ActionResult as described in my question above and on Success I updated the div tag with returned Partial view
  5. From the ActionResult instead of returning complete View I returned the partial view to update the the WebGrid only(return PartialView("_MainView", responceObject);).

I have a running sample application with me. If anybody finds any difficulties to getting this answer then can ask me. I can share the complete working code here. Thanks all especially Karthik for responding my question and all my comments :)

SharpUrBrain
  • 3,180
  • 5
  • 38
  • 56