0

I am in a situation where i want to define the parameter type inside the method. But if i do something like this:

    public class UserModel
    {
        public string InputName { get; set; }
    }

    [HttpPost]
    public ActionResult Index(object obj)
    {
        UserModel test = obj as UserModel;
        ViewBag.Test = test.InputName;

        return View();
    }

The naming convention, that there is supposed to be in my obj when posting a form, does not take place? I think. I wanna do this, because the obj type is located elsewhere. Can this be done somehow? Do I need to overwrite something?

Edit: - Another way of addressing my problem.

When you post a form in a MVC web application. You receive the data by declaring a parameter type in your ActionResult. And here a naming convention takes place right? But what if i don't know the parameter type right away? How can I declare the parameter type later inside the ActionResult method and get the naming convention to happen there?

Hope it makes sense, and sorry for my English!


Thank you for your suggestions! I found another way to approach my problem. And now i am stuck here instead :)

View to String from another controller

Community
  • 1
  • 1
BjarkeCK
  • 5,694
  • 5
  • 41
  • 59

2 Answers2

1
[HttpPost]
     public ActionResult Index(object obj)   
     {    
         UserModel test = new UserModel();
         TryUpdateModel(test);  
         ViewBag.Test = test.InputName;     
             return View();     
      } 

Try this way.

dotnetstep
  • 17,065
  • 5
  • 54
  • 72
0

You're doing yourself a disservice by using MVC and not using strongly typed action parameters. If you have models for your Index action that are that disjoint, you should probably be using multiple controllers each with their own Index action. At the minimum, these should be separate actions in the same controller. Maybe you could handle the decision to call a specific action on the client side:

<script type="text/javascript">
    $(function() {
        $('#myButton').click(function(e) {
            var url = "User/Index";
            data = { InputName: 'username' };
            if(someCondition) {
                url = "User/AnotherAction";
                data = { SomeOtherModelField: 'someOtherValue' };
            }

            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                success: function(e) {
                    alert('post succeeded');
                }
            });
        });
    });
</script>

And your controller could look like:

public class UserController : Controller
{
    [HttpPost]
    public ActionResult Index(UserModel model)
    {
        // do UserModel stuff
        return View();
    }

    [HttpPost]
    public ActionResult AnotherAction(SomeOtherModel model)
    {
        // do SomeOtherModel stuff
        return View();
    }
}
David Fox
  • 10,603
  • 9
  • 50
  • 80