asp.net mvc parameter from page to a partial view

心不动则不痛 提交于 2020-01-01 09:42:07

问题


I'm with a problem, I have a ajax link that pass a parameter, but, the page that it opens does not need that parameter. The page only load 2 partial views, one of those need that parameter passed to the page to load the data correctly, and the other just need to load a form, so, don't need that parameter. How can i acheive this?


回答1:


In order to do what you want, you will need to add the id to the ViewData construct.

var sysfunctions= UnisegurancaService.FunctionsRepository.All();
ViewData["NeededID"] = id
return View(sysfunctions);

then in your view where you render the partial

<%= Html.RenderPartial("GridFunction", (int)ViewData["NeededID"]) %>

Cast as required of course.

Whatever gets pushed in as the second param becomes the .Model in the partial. I would suggest also strongly typing your partials.




回答2:


Try this:

<% Html.RenderPartial("GridFunction", new ViewDataDictionary {{"Id", ViewData["Id"]}}); %>

UPDATED:

And add this in your controller action:

ViewData["Id"] = Id;

UPDATED:

And in your GridFunction partial View you can access Id as:

<%= ViewData["Id"] %>



回答3:


//Controller

  public ActionResult EditFunctions(int id)
    {

        var sysfunctions= UnisegurancaService.FunctionsRepository.All();
        return View(sysfunctions);
    }
    // This is the controller (it does no need the parameter "ID")

//This is the view "EditFunctions"

<div id="formFunction">
<% Html.RenderPartial("FormFunction"); %>
</div>


<div id="gridFunction">
<% Html.RenderPartial("GridFunction"); %> // The grid needs the ID to work correctly but its in the parent page not in the partial call....and the call is an ajax call
</div>



回答4:


If some dependency of the page needs the parameter, then the page needs to know enough to pass the data in, so the page should be able to provide the data. Or, more simply, just add the parameter to the Page's viewdata and be done with it.



来源:https://stackoverflow.com/questions/935915/asp-net-mvc-parameter-from-page-to-a-partial-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!