Reputation: 317
This is what I've tried:
In Controller:
public ActionResult Detail()
{
List<string> list = new List<String>();
return View(list);
}
In View of Detail:
@model dynamic
<!-- some HTML -->
<script>
@Model.add(document.getElementById("input_box").value);
</script>
Problem is, intelli-sense is not detecting that the passed in object is a List so @Model.add doesn't work.
My goal is to pass a list into the view so I can gather data from user inputs, and then use that list of data in my controller. Any ideas?
Upvotes: 0
Views: 142
Reputation: 317
Okay, solved it by creating a global array in the JavaScript of the View, then passing it to a Controller function as a parameter with Ajax.
Upvotes: 0
Reputation: 31
It's not going to be that simple.
Firstly, the Razor statement you used
@Model.add(document.getElementById("input_box").value);
is not a valid C# statement. It will cause an exception when you try to open the page, because the Model type you're using (List<T>
) does not have a method called add
(though it has Add
), and further because that javascript is not valid Razor code either :)
Secondly, you seem to be confused about how the server-client interaction works. You need to carefully think about how what you want to do can be realized--
For you to be able to get information from the client (the user's browser), you first need to render the page, send it to the client, let the user (or whatever) enter the information, and then get them to send it back to a Controller action. At the moment your page is not even rendering, so you couldn't hope to get data from anyone.
This can still be solved in numerous ways, one of which is to use Html.BeginForm(...)
to create a simple form and have an input element and a submit button somewhere in there.
If you can get the user to submit the data back to you, you can then do whatever you like with the data in the previously mentioned Controller action.
Upvotes: 2
Reputation: 148980
The current problem can be solved by using a statically typed model:
@model List<string>
<!-- some HTML -->
<script>
@Model.Add(document.getElementById("input_box").value);
</script>
However, you'll quickly hit another wall when the compiler complains that it doesn't know what document
is. That's because the Razor view is rendered on the server side, but document
is an object provided by the browser on the client side. You simply can't dynamically add elements to this server-side list from the client. You'll need to encode your list somehow for the client to be able to read, say in a JavaScript array. Then dynamically modify the list on the client side, perhaps using the JavaScript .push
method. And then post this back to the controller in a separate action.
Upvotes: 3