开发者

ASP.NET MVC3 Posting form back to same action

I have an action in my HomeController (to keep it simple):

[HttpGet]
[HttpPost]
public ActionResult MyAction(MyOwnViewModel viewModel)
{
    // do some stuff with the viewmodel and return it to the view.
    // Selected values should be preserved inside the viewModel

    return View(viewModel);
}

And I want this action to be called whenever I go to the url /Home/MyAction. It complains that it can't find a MyAction method on the 开发者_如何学编程HomeController and I suspect it is because of the viewModel parameter.

Is there any way to work around this? I would expect the viewModel parameter to just be null.


The answer in this case is to remove one or both of the [HttpGet] and [HttpPost] action filters.

For the edification of others, it is okay to have an action method that accepts a model parameter, with no alternative parameterless version of the method, as long as the model class has a public default constructor.

In such circumstances, the MVC ModelBinder will generate an empty instance of the model class for you.

Look into the IModelBinder interface for more information on custom model binding.


You need one action with none parameter to start it from URL

public ActionResult MyAction()
{

    return View();
}

And use the one you already have to handle the submitted action (this is where HttpGet or HttpPost attribute applied for) from that view so you will have viewModel by then.


as far as I know, I don't know how will and why should you pass your own view model to your action by visiting a URl, but regading your mentioned scenario, I will try to help you fix the missing action behavior and the way to get it discoverable by ASP.NET MVC.

You are correct, because of your viewModel parameter, the default route of MVC3 will not find this action, so you have to define a new route to match with your controller action.

consider the following code:

routes.MapRoute(
             "SearchRoute1",                                              // Route name
             "MyAction/{viewModel}",                             // URL with parameters
             new { controller = "Home", action = "MyAction", viewModel = "" }  // Parameter defaults

         );

you will define something like this inside your Global.ASAX file, specifically inside RegisterRoutes(RouteCollection routes) method, so the routing table of your app be aware of your action method, then you can handle the request as normal.

let me know if this helped you, thanks.


You can't have one ActionResult with two differing HTTP methods. You need to use overloads...

public ActionResult MyAction()
{
     return View(new MyViewModel());
}

And

[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
     // Do your stuff...
     return View(model);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜