简体   繁体   中英

Creating RESTful buttons for ASP.Net MVC 2

I am trying to implement a RESTful MVC project using C# and ASP.Net, accordingly I have a controller with methods distinguished by request types like this simplistic example:

[HttpGet, ActionName("Instance")]
public ActionResult Get(string id) {
    //Get
}

[HttpPut, ActionName("Instance")]
public ActionResult Update(string id, Instance instance) {
    //Update
}

[HttpDelete, ActionName("Instance")]
public ActionResult Delete(string id) {
    //Delete
}

On the view I want to display the Instance and have buttons to update and delete which will invoke the appropriate actions above. What is the best way to create these buttons so that they generate a request with the appropriate request type?

This should help: http://blog.osbornm.com/archive/2009/11/24/overriding-the-http-verb-in-asp.net-mvc-2.aspx

Additionally, for DELETE action (where you need only Id), you can have a different small form and use HttpMethodOverride method of html helper. See http://geekswithblogs.net/michelotti/archive/2010/01/08/implementing-a-delete-link-with-mvc-2-and-httpmethodoverride.aspx

<%: Html.ActionLink("Get button", "Instance", new { id = "123" }) %>

<% using (Html.BeginForm("Instance", "ControllerName", new { id = "123" }, FormMethod.Post)) %>
    <%: Html.HttpMethodOverride(HttpVerbs.Put) %>
    <%: Html.TextBoxFor(x => x.Prop1) %>
    <%: Html.TextBoxFor(x => x.Prop2) %>
    <input type="submit" value="Put button" />
<% } %>

<% using (Html.BeginForm("Instance", "ControllerName", new { id = "123" }, FormMethod.Post)) %>
    <%: Html.HttpMethodOverride(HttpVerbs.Delete) %>
    <input type="submit" value="Delete button" />
<% } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM