How to pass data from razor view to controller in

2019-04-14 07:10发布

问题:

I have a model that I'm using to pass data from my view to my controller but I have some unbound from textboxes and dropdownlists. How can I pass that unbound data from my view back to my controller using ViewData or ViewBag....or something. Thanks!

回答1:

Can you give an example? It looks as if you're mixing up your terminology a bit. You don't generally pass data from a view to a controller except via a POST/GET. I'm going to assume that's what you meant. You can get any data into your controller's action method via a parameter with the same name or using a FormCollection.

public ActionResult SomeMethod(
                       string yourUnboundTextBoxName, 
                       FormCollection colleciton) { }

In your view it might have something like:

<div>
    <input type='text' name='yourUnboundTextBoxName' />
</div>

MVC will automatically take the value of yourUnboundTextBoxName and insert that value into the parameter of the same name. Or you can use the FormCollection and get the value from there. FormCollection["yourUnboundTextBoxName"]



回答2:

You can't pass data from the view to the controller using the ViewBag. The view (or at least the HTML generated from the view) can post data back to the controller using forms and the default binder would allow you to have objects provided as arguments to the controller's method.

If you want lots of data you can pass arrays, etc. using the correct naming guidelines and the default binder.

Other than that you would need additional data for us.



回答3:

You can send a model back to a controller in several methods. Here is just one of them. Since it seems like you only want a few items at a time sent back, possibly dynamically - this approach gives you a bit of control over what to send back and then uses a .ajax() request to do it.

Asp.Net MVC Passing an object from Url.Action in View to Controller

from the link above:

$.ajax({
   url: '@Url.Action("ControllerActionResult")',
   type: 'POST',
   data: JSON.stringify(model), //you can serialize a form here as well OR simply put in the name value pairs of your data, ex. myTextBox='something'
   dataType: 'json',
   processData: false,
   contentType: 'application/json; charset=utf-8',
   success: OnSuccess
});

Note the ajax docs jQuery .ajax()