简体   繁体   中英

Update modal data after partial view refresh

I have a select box in a main view. That view has inside a partial view. When the value on that select box changes I want to reload the partial view (with some new data from a model) and update a modal content with that new data .

I can reload the partial view successfully, my problem is What is the best approach for the modal update?

Options I see:

  • define the modal in the main view but don't know how to access the data from the model passed to the partial view;
  • define the modal inside partial view but is this a good practice?
  • pass the model with all information to the main view, but this way, when the value on the select box changes I need to refresh all the view, and I prefer to reload only the partial view.

What I understand from you question is that, you have a main view which has a SelectList control on selection change of that the SelectList you want to update a portion of view (the partial view), for that portion you may be using a partial view. If that is the case follow the following steps, hopefully this will help you in achieving your task:

Step: 1: lets say this is your main view [MainView.cshtml]

@model yourProjectNameSpace.SomeModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@ViewBag.Title</h2>

<select id='yourSelectList'>
  <option value="1">Option One</option>
  <option value="2">Option two</option>
</select>

<div id="PartialAreaToUpdate">
    @Html.Partial("_YourPartialView", Model)
</div>

@section scripts
{
<script>
        $('#yourSelectList').change(function () {
            var selectedvalue = $(this).val();
            if (!selectedvalue ) {
                return;
            }
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetYourUpdatedPartial", "YourControllerName")',
                data: { selectedvalue: selectedvalue},
                success: function (response) {
                     $('#PartialAreaToUpdate').html('');
                     $('#PartialAreaToUpdate').html(response);
                }
            });
        });
</script>
}

step.2: your controller code will look like

    public class YourControllerNameController : Controller
    {
        public ActionResult GetYourUpdatedPartial(string selectedvalue)
        {
            var model = getUpdtedDataFromYOurStor(selectedValue);
            return View("_YourPartialView", model);
        }
    }

step. 3: Finally your partial view [ _YourPartialView.cshtml ]

@model yourModel

your logic of rendering data will go here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM