0

This is my head section with scripts

<head>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")

    <script type="text/javascript">
        $(function () {
            $("#SelectHouse").click(function () {
                var selected = $("#SelectedHouseDetailsId option:selected").text();
                $("#SelectedHouseDetailsText").val(selected);
                var idd = $("#Model.Reservation.Id").text();

            });    
        })
        $.ajax({
            url: "/ClientReservations/GetView",
            type: "GET",
            dataType: "html",
            data: {id: idd,name: selected}
        })
                .success(function(result){
                    $('#divForSelectHouse').html(result)
                })
        }
    </script>   

    <script type="text/javascript">
        function MyFunction() {
            var selected = $("#SelectedHouseDetailsId option:selected").text();
            $("#SelectedHouseDetailsText").val(selected);
        }
    </script>

</head>

I would like to call method in controller in that way that after click button in form section

<div class="form-group">
        @Html.Label("Domki", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.SelectedHouseDetailsId, Model.Houses)
        </div>
        <div class="col-md-offset-2 col-md-10">
            <input type="button" class="SelectHouse"
                   value="Wybierz domek" id="SelectHouse" />
        </div>
    </div>

I pass two parameters to following method

public ActionResult GetView(int id,string name)
        {
            ReservationHouseDetails houseDetails=null;
            repository.GetHousesForReservation(id).Where(item => item.Name.Equals(name)).ForEach(item => houseDetails = new ReservationHouseDetails()
            {
                House=item,
                Meal = repository.GetHouseMealForReservation(item.Id),
                Participants = repository.GetParticipantsHouseForReservation(item.Id)
            });

            return PartialView("ReservationHouseDetails", houseDetails);
        }

Returned PartialView should be put into div section w view Details.cshtml

<div id="divForSelectHouse">


    </div>

2 Answers2

0

first you need render partial view to string after that return partial view as string.

Add static class to achieve that:

   public static class RenderViewToString
{
    public static string RenderPartialViewToString(Controller thisController, string viewName, object model)
    {
        // assign the model of the controller from which this method was called to the instance of the passed controller (a new instance, by the way)
        thisController.ViewData.Model = model;

        // initialize a string builder
        using (StringWriter sw = new StringWriter())
        {
            // find and load the view or partial view, pass it through the controller factory
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(thisController.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(thisController.ControllerContext, viewResult.View, thisController.ViewData, thisController.TempData, sw);

            // render it
            viewResult.View.Render(viewContext, sw);

            //return the razorized view/partial-view as a string
            return sw.ToString();
        }
    }
}

and then using like this:

//this  = inside Controller
var html = RenderViewToString.RenderPartialViewToString(this, "ReservationHouseDetails", houseDetails);

return Content(html);

How to Render Partial View into a String

Hamed Javaheri
  • 538
  • 3
  • 13
  • I applied this proposition, but when i click button selectHouse there are no interaction. My view Details.cshtml in div section is not changing. Is it the matter of javascript? –  Aug 13 '17 at 12:59
  • did you add break point inside GetView controller? did you change ajax data type to text? – Hamed Javaheri Aug 13 '17 at 15:47
  • It is like script started from $ajax is ignored, click button doesn't give any result. –  Aug 13 '17 at 18:42
  • In ajax error section status is 404, so is this method GetView is proper? –  Aug 13 '17 at 19:02
  • This is saying the resource you are trying to do a GET to is not there. The path you are doing a GET to is probably incorrect.where is you controller and Partial View exactly? – Hamed Javaheri Aug 14 '17 at 02:58
  • Controller path: Controllers/ClientReservationsController/GetView PartialView path: Views/ClientReservations/ReservationHouseDetails.cshtml –  Aug 14 '17 at 12:47
  • I think you must check "selected" and "idd" for null.in google chrome developer tools in network tab you can check what request send to server. – Hamed Javaheri Aug 14 '17 at 15:43
  • what was problem? – Hamed Javaheri Aug 14 '17 at 17:11
  • Invalid path to method controller, his attribute,content type and format of given parameters in ajax script. –  Aug 14 '17 at 17:24
0

Finally i have solution, method in controller must have attribute

[HttpPost]
        public ActionResult AjaxMethod(int id,string name)
        {
            ReservationHouseDetails houseDetails=null;
            repository.GetHousesForReservation(id).Where(item => item.Name.Equals(name)).ForEach(item => houseDetails = new 
    ReservationHouseDetails()
                {
                    House=item,
                    Meal = repository.GetHouseMealForReservation(item.Id),
                    Participants = repository.GetParticipantsHouseForReservation(item.Id)
                });
                return PartialView("~/Views/Shared/ReservationHouseDetails.cshtml", houseDetails);
            }

Corrected script with dropdowlist.

<script type="text/javascript">
            $(function () {
                $(".btnGet").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "/ClientReservations/AjaxMethod",
                        data: '{id: "' + $("#idValue").val() + '",name:"' + $("#SelectedHouseDetailsId option:selected").text() + '" }',
                        contentType: "application/json; charset=utf-8",
                        dataType: "text",
                        success: function (response) {
                            $('#SelectHouse').html(response)
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        },
                        error: function (response) {
                            alert(response.responseText);
                            console.log(response.responseText)
                        }
                    });
                });
            });
    </script>

<input type="hidden" id="idValue" value=@Model.Reservation.Id />
        <input type="button" id="btnGet" value="Wyświetl" />

<div class="form-group">
            @Html.Label("Domki", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("SelectedHouseDetailsId", Model.Houses)
            </div>
        </div>