简体   繁体   中英

How to pass data to partial view after reload

Controller:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class ExperimentalController : Controller
{
    public ActionResult ReloadTest1()
    {
        string temp = DateTime.Now.ToString();
        ViewBag.Time = temp;
        return View();
    }

    public PartialViewResult ReloadTest1Partial()
    {
        string temp = DateTime.Now.ToString();
        ViewBag.Time = temp;
        return PartialView();
    }
}

View:

@{
    ViewBag.Title = "ReloadTest1";
    string time = this.ViewBag.Time;
    ViewData["date"] = time;

    ViewBag.TheTitle = "test";
}

<h2>ReloadTest1</h2>

<select id="iSelect" name="iSelect" >
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>


<div id="myPartialViewContainer">
    @{Html.RenderPartial("_ReloadTest1Partial", null, new ViewDataDictionary { {"vb", ViewBag}});}
</div>

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
    $('#iSelect').on('change', function () {
        $("#myPartialViewContainer").load('@(Url.Action("ReloadTest1Partial", "Experimental", null, Request.Url.Scheme))')
    })
</script>

Partial View:

@{
    var vb = ((dynamic)ViewData["vb"]);
}

<div>
    <span>@vb.Time</span>
</div>

What is not working:

Passing the viewbag/viewdata directly from controller to partial view because mvc does not accept that to happen.

What is working:

from the above code you can see that the partial view gets the data ONCE with the Html.RenderPartial method and the viewbag passing down. the reload does work on change of the selected object in the dropdown

What is needed:

I need to pass data to the partial view when it is reloaded or afterwards, this is mainly a test setup but i finally want to be able to update tables dependant on the select value.

If somone is able to give me a working example please do so.

In your controller you;re using ViewBag to set custom value, but in your view you are working with ViewData as well as referring to a different name (you're setting ViewBag's Time property in controller, but you expect ViewData's vb property in the view).

Change your view to expect model`:

@model MyModel
@{
    string time = "";
    if (ViewData["Time"] != null) 
    {
       time = ViewData["Time"];
    } 
}

<div>
    <span>@Model.Time</span>
</div>

And change you controller to pass it:

public ActionResult ReloadTest1()
{
    var model = new MyModel {Time = DateTime.Now.ToString()};
    return View(model);
}

public PartialViewResult ReloadTest1Partial()
{
    var model = new MyModel {Time = DateTime.Now.ToString()};
    return PartialView(model);
}

And you master view file will look like this:

@model MyModel
<div id="myPartialViewContainer">
    @{Html.RenderPartial("_ReloadTest1Partial", model);}
</div>

And create your model:

public class MyModel
{
    public string Time {get;set;}
}

As a side not, it's always preferable to use a strongly-typed model instead of ViewBag or ViewData as you can get compilation errors and IntelliSense

Final solution:

Controller:

 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace RolloutTool.Controllers { [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] public class ExperimentalController : Controller { public ActionResult ReloadTest1() { var model = new RolloutTool.Models.ExperimentalViewModels.MyModel { Time = DateTime.Now.ToString() }; string temp = DateTime.Now.ToString(); ViewBag.Time = temp; ViewData["Time"] = temp; return View(model); } [HttpPost] public PartialViewResult ReloadTest1Partial(string test) { var model = new RolloutTool.Models.ExperimentalViewModels.MyModel { Time = DateTime.Now.ToString() }; string temp = DateTime.Now.ToString(); ViewBag.Time = temp; ViewData["Time"] = temp; return PartialView("_ReloadTest1Partial", model); } // GET: Experimental public ActionResult Experimental() { ViewBag.Message = "Your contact page."; ViewBag.TestValue = 10; string[] temp = { "alpha", "beta", "gamma", "delta" }; ViewBag.names = temp; int temp2 = temp.Length; ViewBag.nameslength = temp2; return View(); } } } 

View:

 @{ ViewBag.Title = "ReloadTest1"; string time = this.ViewBag.Time; ViewData["date"] = time; ViewBag.TheTitle = "test"; } @model RolloutTool.Models.ExperimentalViewModels.MyModel <h2>ReloadTest1</h2> <select class="chosen-select" id="iSelect" name="iSelect"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <div id="myPartialViewContainer"> @{Html.RenderPartial("_ReloadTest1Partial", Model);} </div> @Styles.Render( "~/content/chosen/chosen.css", "~/content/chosen/prism.css", "~/content/chosen/style.css", "~/content/bootstrap.css", "~/content/Site.css") <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/chosen/chosen.jquery.js"></script> <script src="~/Scripts/chosen/prism.js"></script> <script> var config = { '.chosen-select': {}, '.chosen-select-deselect': { allow_single_deselect: true }, '.chosen-select-no-single': { disable_search_threshold: 10 }, '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' }, '.chosen-select-width': { width: "95%" } } for (var selector in config) { $(selector).chosen(config[selector]); } </script> <script src="~/Scripts/jquery-1.10.2.js"></script> <script> $('#iSelect').on('change', function () { getPartial(); }) </script> <script> function getPartial() { var tempSelect = document.getElementById("iSelect"); var tempResult = tempSelect.options[tempSelect.selectedIndex].text; $.ajax({ url: "ReloadTest1Partial", type: "POST", data: {'test' = tempResult}, //if you need to post Model data, use this success: function (result) { $("#myPartialViewContainer").html(result).find("select").each(function () { $(this).chosen({}); } }); } </script> 

 @{ string time = ""; string temp = ""; if (ViewData["vb"] != null) { temp = "1"; time = ((dynamic)ViewData["vb"]).Time; } else if (ViewContext.Controller.ViewBag.Time != null) { temp = "2"; time = ViewBag.Time; } else if (ViewData["Time"] != null) { temp = "3"; time = (string) ViewData["Time"]; } } @model RolloutTool.Models.ExperimentalViewModels.MyModel <div> <span>@time</span> <span>@Model.Time</span> <span>@temp</span> </div> <select class="chosen-select"></select> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/chosen/chosen.jquery.js"></script> <script src="~/Scripts/chosen/prism.js"></script> 

This updates the partial view correctly AND reloads the chosen-select dropdowns. (see styles and scripts not working in partial view )

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