开发者

Calling controller from view?

  • Controller1 - Index() > return View1
  • Controller2 - Index() > return View2
  • Controller3 - Index() > return View3 ....
  • Controller1000 - Index()> return View1000

  • ControllerAAAA - GiveMeSomething(....) > return PartialView1

Objective: Add the result of PartialView1 on the View 1 to 1000.

Solutions: The controllers 1 to 1000 could inherit from a special class that holds the strongly typed object needed for the ControllerAAAA and then I could call, from the view, the PartialView1 and pass the object needed. I think this is the correct way to do i开发者_JS百科t.

Other option: I also could have some ajax on the view to call the controller.

However I would like to know if I could simple call the Controller AAAA from the View1 to View 1000 and avoid the inherited class? Something like:

<%= CallController("GiveMeSomething", "ControllerAAAA", new Parameters(value1: "something", value2: 11 )%>

Is this possible? How?


You can use

<% Html.RenderAction<MyController>(m => m.LatestNews()); %>

I think you need to the MVC futures for this... which you can download from here: MVC Futures

But you should be careful when using this as its does not conform to the MVC pattern, your views should be dumb and just display data that is handed to it. Although it can be handy for doing things like navigation menu's.


While it may be possible, in the MVC world this definitely is a poor practice.

If you're trying to render different partial views, the logic used to render them should be in the Controller where it belongs. The View is strictly for rendering the Model (or ViewModel) that was delivered to it by the Controller.

With a little more description of the reason you're trying to do what you're doing...we might be able to make a better suggestion.


I agree with Justin - you should give some serious thought to exactly what you want to do here. I'm sure that if you provide more details, we'll be able to make better suggestions. If this is what you really want to do, you can use the outer edge's suggestion.

Dryadwoods: I also could have some ajax on the view to call the controller.

If you really want to make this call using AJAX, jQuery provides an easy way to do this:

$(document).ready(function() {
    $('#container').load('/url/to/action', { 
        Value1: <%= Model.Value1 %>,
        Value2: <%= Model.Value2 %>
    });
});

In this example, container is an DOM node with ID "container". An AJAX call will be made to the specified URL with the specified JSON values. In your controller, you would declare the following action:

ActionResult SomeAction(string Value1, string Value2)
{
    // Return a partial
}

I didn't test any of this code, so you might need to make a few adjustments. Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜