Controller can't find DELETE route, but the method is in the controller - http-delete

I am building a small sinatra app but came across an issue. My controller function for DELETE isn't being found.
ApplicationController
delete '/stories/:id' do
if logged_in?
#story = Story.find_by_id(params[:id])
if #story && #story.user_id == current_user.id
params.delete("_method")
#binding.pry
#story.destroy
redirect to "/users/show"
else
redirect to "/session/login"
end
end
end
DELETE Form Action
Title: <%= #story.title %><br>
Story: <%= #story.content %><br>
<form action="/stories/<%= #story.id %>" method="POST">
<input type="hidden" id="hidden" name="_method" value="DELETE">
<input type="submit" value="Remove Story">
</form>
Error
class ApplicationController
delete '/stories/13' do
"Hello World"
end
end
I also can't pry into this route

You need to use the following middleware that will translate
<input type="hidden" id="hidden" name="_method" value="DELETE"> to http delete
use Rack::MethodOverride

Related

Controller doesn't redirect after form submit

I'm new to ASP.net MVC and I am struggling to make this work at the moment. I have a controller method called Add, it looks like this:
public ActionResult Add()
{
// check user is authenticated
if (Request.IsAuthenticated)
{
return View();
}
return RedirectToAction("Index", "Home");
}
//
// POST: /Home/Add
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(string title, string description, string priority, string color, FormCollection collection)
{
if (ModelState.IsValid)
{
// create instance of todo object
todo obj = new todo();
try
{
// gather fields
obj.priority = Convert.ToInt32(priority);
obj.color = Convert.ToInt32(color);
obj.title = title;
obj.description = description;
todosDataContext objLinq = new todosDataContext();
// get the users id, convert to string and store it
var userid = Membership.GetUser().ProviderUserKey;
obj.userid = userid.ToString();
// save
objLinq.todos.InsertOnSubmit(obj);
objLinq.SubmitChanges();
return RedirectToAction("Index", "Home");
}
catch
{
return View(obj);
}
}
return RedirectToAction("Index", "Home");
}
If data is sent via POST to the method, it should add the data to the database. That is working fine and everything is added correctly. However, the RedirectToAction is not firing, and the application gets stuck at /Home/Add, when it should redirect to /Home/Index. The view loads however, so it shows /Home/Index but the URL says /Home/Add.
Here is a copy of the partial view that contains the form:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<todo_moble_oauth.Models.todo>" %>
<% using (Html.BeginForm()) { %>
<%: Html.AntiForgeryToken() %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<h3>Title:</h3>
<div class="editor-field">
<input type="text" name="title" />
</div>
<h3>Description:</h3>
<div class="editor-field">
<input type="text" name="description" />
</div>
<h3>Priority:</h3>
<div class="editor-field">
<select name="priority">
<option value="1">Low</option>
<option value="2">Medium</option>
<option value="3">High</option>
</select>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<h3>Color:</h3>
<input type="radio" name="color" id="radio-choice-1" value="0" checked="checked" />
<label for="radio-choice-1">None</label>
<input type="radio" name="color" id="radio-choice-2" value="1" />
<label for="radio-choice-2">Red</label>
<input type="radio" name="color" id="radio-choice-3" value="2" />
<label for="radio-choice-3">Blue</label>
<input type="radio" name="color" id="radio-choice-4" value="3" />
<label for="radio-choice-4">Yellow</label>
</fieldset>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
So data is being sent to the database and stored, however the redirect is broken.
Turns out it is an issue with jQuery mobile, this threads solution resolved the issue for me:
jQuery Mobile/MVC: Getting the browser URL to change with RedirectToAction

Why my checkBox statement doesnt works?

Why my checkBox statements doesnt works?I've used session as you seen(because my homework so dissmiss if it usefull or not):
<form id="ShoppingCart" action="Final.aspx">
<input type="checkbox" runat="server" id="CallOfDutyCheckBox" />
<%
if (CallOfDutyCheckBox.Checked)
Session["Username_CallOfDutyCheckBox_price"] = "5";
%>
<input type="submit" value="Buy It" />
</form>
<form id="Final">
<div>
<%
Response.Write(Session["Username_CallOfDutyCheckBox_price"]);
%>
</div>
</form>
Do you understand when you click the checkbox, the code at the server does not run yet? Click submit to submit the form with the value of the checkbox.

How do I post back to an MVC controller action via Javascript

Currently I have a aspx page that is defined as:
<%Using Html.BeginForm("SaveNotifications", "Notifications", FormMethod.Post, New With {.id = "NotificationForm"})%>
...
<tr>
<td colspan="3">
<input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" />
</td>
</tr>
</table>
</fieldset>
<%End Using %>
I want to change this so that my input button fires a javascript function so that I can do some complex validation of the form and THEN post to the controller.
I changed my submit button to:
<input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" onclick="onSave(); return false;" />
The onSave() method would fire but not post back to the controller.
The controller is defined as:
<HttpPost()> _
<MultiButton(MatchFormKey:="SaveNotifications", MatchFormValue:="Save")> _
Function SaveNotifications(ByVal NotificationForm As FormCollection) As ActionResult
...
End Function
How do I change this so that the javascript fires, runs my validation and then hits this controller action?
Thanks
Change your submit button to
<input type="submit" id="SaveNotifications" name="SaveNotifications" value="Save" class="t-button" onclick="return onSave();" />
Then in the javascript onSave() function, return true or false depending on the validation.
function onSave()
{
var isValid = true;
// ... do your validation ...
// ie:
// if (field1.value.length == 0)
// isValid = false;
// returning true will post the form. False will halt it.
return isValid;
}

how can we cal two servlets from the same html page?

I need to design a page to register as well as login a user.By clicking login button login servlet should be called.And on clicking register button,register servlet will be called.how can i do this?
Having two forms that post to different places is the simplest method
Name your buttons:
<input type="submit" name="form_action" value="Login" />
and
<input type="submit" name="form_action" value="Register" />
When it comes to processing the form, just hookout form_action and it should equal Login or Register.
This requires some more server-side logic but should work if you need your two forms to be tightly combined.
You can include some Javascript code for this.
<form name="Form1" method="post">
Your Name <input type="text" name="text1" size="10" /><br />
<INPUT type="button" value="ButtonLogin" name=button1 onclick="return OnButtonLogin();">
<INPUT type="button" value="ButtonRegister" name=button2 onclick="return OnButtonRegister();">
</form>
like this:
<script language="Javascript">
<!--
function OnButtonLogin()
{
document.Form1.action = "Login.do"
document.Form1.target = "_blank";
document.Form1.submit();
return true;
}
function OnButtonRegister()
{
document.Form1.action = "Register.do"
document.Form1.target = "_blank";
document.Form1.submit();
return true;
}
-->
</script>

ASP.NET MVC url search parameter without question mark

I have a route defined as:
routes.MapRoute("AllUsers",
"Users/Search/{Search}", new {
Controller = "Users", action=
"Index"});
and the form as:
<% using (Html.BeginForm("Index", "Users/Search/", new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
<input id="searchBox" name="search" type="text" />
<input type="submit" id="submit" value="Search" /><%} %>
Currently as expected this creates a url of
../Users/Search/?search=searchTerm
but what I would like is:
../Users/Search/searchTerm
How is this possible? I thought of using javascript, but this seems a little dirty. Is there a more streamlined way of accomplishing this?
You cannot do that with an HTML form. Though you can mimic the behavior with JavaScript.
How about a server-side redirect?
You could do:
<input type="submit" id="submit" value="Search"
onclick="$('form').attr('action', $('form').attr('action') + $('#searchBox').val());" />
Which seems a little ugly. You could also not use a form and have this:
<input type="button" id="submit" value="Search"
onclick="window.location.href = 'search/' + $('#searchBox').val();" />
Outside of this, you could allow the original submit to go to the weird url, but use RedirectToAction in your controller.
Using jQuery you could something like this:
<script type="text/javascript">
$(function(){
$("#submit").click(function(){
document.location.href = $("form").attr("action") + $("#searchBox").val();
return false;
});
});
</script>
Try to change like this:
routes.MapRoute("AllUsers",
"Users/Search/{id}", new { Controller = "Users", action= "Index"});
and the form as:
<% using (Html.BeginForm("Index", "Users/Search/",
new { RouteValue = "AllUsers" }, FormMethod.Get, new { id = "searchForm" })){%>
<input id="searchBox" name="id" type="text" />
<input type="submit" id="submit" value="Search" /><%} %>
Not tested, but "id" is default route value which are not creating "?name=value".

Resources