开发者

Handing forms in ViewUserControls

开发者 https://www.devze.com 2022-12-10 06:44 出处:网络
I am rendering out a ViewUserControl (.ascx file) in a view: <% Html.RenderPartial(\"Comments\", Model.Comments); %>

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

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

This ViewUserC开发者_Python百科ontrol 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?


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...


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) ...


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).

0

精彩评论

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