views:

111

answers:

3

I am rendering out a ViewUserControl (.ascx file) in a view:

<% Html.RenderPartial("Comments", Model.Comments); %>

This ViewUserControl shows associated comments on an entry. I would like this control to render out a form as well, so users of my application can contribute.

How would you add a form to a ViewUserControl and handle it's postback?

+1  A: 

Just add the form in there the same as you would on any page. In MVC, the form does not postback as such - it simply submits itself and its content (input controls) via HTTP Post to a URL.

Simply create an action in your controller (and hence a URL) which the form will post and do whatever activity is required there...

Paul
So render out the form in the PartialView and create an ActionResult in the controller the PartialView is used in?
roosteronacid
Correct. The ActionResult can be in any controller really, but will probably fit best in the same one the PartialView is in...
Paul
+1  A: 

There is no postaback, like in standard asp.net, there can be only form tag that posts data to some url (controller/action).
Inside your partial user control, write:

<form action="controller/actionname" method="post">
<input type="text" name="inputText" />
<input type="submit" value="Post data to server" />
</form>

In MVC, only input type="submit" triggers form submit. In standard ASP.NET webforms, you can have many Linkbuttons, Buttons, ... but under cover, they all triggers this simple click on input type="submit" through javascript event. One form can post data to only one URL (controller/action), but that can be changed with javascript (as we can see in html source of 'old' asp.net webforms).

then, in controller you can handle post data:

[AcceptVerb(HttpVerb.Post)] // optionally 
public ActionResult ActionName(string inputText) ...
Hrvoje
A: 

Like others have answered already, you simply render a form and handle it's submit with an ActionResult.

For example, if your form (which could be rendered anywhere in your site) was submitting to http://www.yoururl.com/home/save, you would create an ActionResult method named save on the home controller to handle the submit (likely post/get method).

Chad