Http.BeginForm does not post - asp.net-mvc

I have spent about 3 hours trying to figure out why this view is not posting. It is probably a really dumb mistake. When I click on my submit button absolutely nothing happens. I have several submit forms completed already but this one just does not want to work!
This is my cshtml file
#{
ViewBag.Title = "ZipCodeUtility";
}
<h2>ZipCodeUtility</h2>
#using (Html.BeginForm("GetZipsByDistance", "Dev", FormMethod.Post))
{
<span>Find zip codes within "x" miles from me</span>
<br />
#Html.TextBox("DistanceMiles")
<input type="button" value="GetZipsByDistance" />
}
And here is my controller action
public ActionResult GetZipsByDistance(string DistanceMiles)
{
FileStream zipFile = new FileStream("~/StaticData/2013_Gaz-zcta_national.txt", FileMode.Open);
Utility.ZipCodeUtility.ZipCodes zips = Utility.ZipCodeUtility.ZipCodeReader.ReadZipCodes(zipFile);
var closeCodes = zips.FindLessThanDistance(zips[46324], double.Parse(DistanceMiles));
ViewBag.Codes = closeCodes;
return View(new ViewModels.ViewModelBase());
}
I have tried comparing this view and controller with many of my others that do work and everything seems legit. I tried viewing the source in chrome to see if there was something funky going on but there doesnt seem to be either. If I hover over the button the browser does not display the url either..

You have to change the input type:
<input type="submit" value="GetZipsByDistance" />
A regular button will not post the form.

Related

Route to a POST method with model and id

I want to pass in two Ids to my method. The method is called DeleteAttendee and is on my SessionController in the Training area.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteAttendee(int sessId, int attId)
I have created a link to get there that takes you to https://localhost:<port>/Training/Session/DeleteAttendee?sessId=1&attId=3.
<a asp-action="DeleteAttendee" asp-route-attId="#item.Attendee.Id" asp-route-sessId="#Model.Id">Delete</a>
Using the default routing, this page can't be found. What do I need to change or set up to route to this method?
Edit: Apparently the problem is that the link is performing a GET, but I need it to POST. How do I change it?
I think you can accomplish what I want to do with a button control. It will actually work better for me now if I can pass in the model and a specific id. I tried the button below. It looks correct in the markup, but the id keeps getting replaced with the sessionId when the button is clicked.
<button formaction="/Training/Session/DeleteAttendee/#item.Id" formmethod="post">Edit</button>
Can you use a ActionLink instead?
#Html.ActionLink("Delete", "DeleteAttendee", "Session", new { sessId = Model.Id, attId = item.Attendee.Id })
I ended up using a submit button that calls javascript and added the value to the viewmodel to get this done.
On the page:
<input type="hidden" asp-for="SelectedAttendeeId" />
<input type="button" onclick="DeleteAttendee(#item.Id)" value="E" />
In javascript:
function DeleteAttendee(attendeeId) {
var selectedAtt = $('#SelectedAttendeeId');
selectedAtt.val(attendeeId);
var model = $('#frmSession').serialize();
$.post('/Training/Session/DeleteAttendee', model, function (data) {
// success logic here
});
}

MVC5 : The resource cannot be found

I am fetching data from a table and displaying it. Every row in the webpage will have a edit hyperlink. That pops up a edit window for respective row. The contents of the pop up are replaced by the #Html.Partial() function. now the form gets submitted from the Partial view. The Interesting fact is first time I edit any row it works fine. However the second time I am getting the following error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Edit
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2623.0
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "SerialNumber,ProjectName,Nature,Phase,StartDate,EndDate,ProjectLead,LeadAlias,Onsite,OffShore,ProjectDetail,EditedBy,CreatedBy")] ProjectModel projectModel)
{
projectModel.EditTime = DateTime.Now;
if (ModelState.IsValid)
{
db.Entry(projectModel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(projectModel);
}
The form gets submitted using the following button:
<input type="submit" value="Save" class="btn btn-default" formaction="Edit" formmethod="post" />
Please let me know if anything else do you need. Thanks in advance.
#shyju 's answer really helped I changed the formaction and it worked

Want to simulate postback in ASP.Net MVC

suppose i have one form and form has two div container. one div container has few textboxes for submiting login details and another div also has few textboxes those related to register. now my home controller has two action method one is login and another is register. i want that when user click on login button then i will submit form through jquery but before submit i will change action url. the same way i want to call register action method when user click on register button. please guide me how could i do this in mvc with jquery. please help me with sample code.
another person answer like in other forum.
#model MvcForums.Models.StudentModel
#{
using(#Html.BeginForm("Create","Student", FormMethod.Post))
{
<label> Name</label>
#Html.TextBoxFor(m=>m.FirstName) <br/>
<label> From country:</label>
#Html.DropDownListFor(m=>m.CountryId, Model.Countries,"--please select-- ") <br/>
<input id="btnSave" value ="Login" type="submit" name="commandName"/>
<input id="btnRegister" value ="Register" type="submit" name="commandName"/>
}
}
[HttpPost]
public ActionResult Create(StudentModel studentModel, string commandName)
{
if(commandName == "Login")
{
}
else if(commandName == "Register")
{
}
return View("Index");
}
after reading his answer some confusion occur in my mind because i am newbie in mvc and those are as follows
first of all ur code is not readable for ill format. i am new in mvc....just learning it. after reading ur code some confusion occur.
1) why extra bracket u gave #{ }
2 u use <label> Name</label> in form building code. in html4 is there any tag ? is it html5 specific tag ?
3) #Html.DropDownListFor(m=>m.CountryId, Model.Countries,"--please select-- ")
when u building dropdown why u did not specify value & text filed.......how mvc can understand what field will be value & what will be text ? u just bind the model with DropDownListFor()
4) just see it
<input id="btnSave" value ="Login" type="submit" name="commandName"/>
<input id="btnRegister" value ="Register" type="submit" name="commandName"/>
both the button name is commandName ? is it correct ?
when user click on any button then how button name will be pass to
public ActionResult Create(StudentModel studentModel, string commandName)
Create() method ? please tell me how implicitly command name will be pass to Create() and how commandName variable at server side can hold the button name.
i have too much confusion after reading ur code. if possible please discuss all my points in details. thanks
i want that when user click on login button then i will submit form
through jquery but before submit i will change action url. the same
way i want to call register action method when user click on register
button.
1. Event on button click:
$(function(){
$("#btnSave").click(function(){
$("#btnSave").closest("form").attr("action", "/home/test");
});
});
2. MarkUp:
<form method="POST" action="/home/test1" >
<input id="btnSave" value="Login" type="submit" name="commandName"/>
</form>
3. Server side:
[HttpPost]
public ActionResult Test(string commandName)
{
return null;
}
1) Razor syntax reference http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
2) The <label> is not specific html5 tag but it have additional attribute in html5, http://www.w3schools.com/tags/tag_label.asp
3) You can build your IEnumerable of SelectListItem in which specified Text and Value
4) The input name commandName is not important if you don't want to catch client value value ="Login" on server side,

asp.net mvc jquerymobile redirectotroute doesn't change url

I've got an mvc4/jquerymobile application, and I'm having a hard time figuring out why, after returning a RedirectToRoute(rvd) from a controller-action, the redirected-to url is not shown.
I start the process on an Edit page with a form at http://localhost/Report/Params/9. I edit the form, submit it, and the Report controller, Params [HttpPost]action fires up. It validates the form values, munges them around a bit, and then adds the lot of them to a RouteValueDictionary, along with my controller ("Report") and new action ("Render") properties.
This all happens correctly, and I'm taken to the "Render" view, but the URL displayed in the browser remains http://localhost/Report/Params/9
I would like the browsers url to show http://localhost/Report/Params/9?p1=1&p2=2&p3=3 instead, because I want the users to be able to bookmark a parameter-set for later use.
What am I missing? I think the issue is related to jquerymobile's handling of the submit button click. I tried to mitigate that with data-ajax=false, but it doesn't seem to have helped any.
<button type="submit" data-theme="b" name="submit" value="submit-value" data-ajax="false">
Submit
</button>
Thanks
Edit: Here's a close replica of my redirecting function...
public ActionResult Params(FormCollection Params ) {
RouteValueDictionary rvd = new RouteValueDictionary();
// example values //
rvd.Add("controller", "Report");
rvd.Add("action", "Render");
rvd.Add("id", 10);
rvd.Add("p1", 1);
rvd.Add("p2", 2);
rvd.Add("p3", 3);
RedirectToRouteResult rrr = RedirectToRoute(rvd);
return rrr;
}

submitting form using hyperlink instead of button

I have created a link for deletion in asp.net mvc3 razor view like this:
<td>
#Html.ActionLink("Edit", "EditCategory", new { id = item.CategoryId }) |
#Html.ActionLink("Details", "Details", new { id = item.CategoryId }) |
#using (Html.BeginForm("Delete", "Admin"))
{
#Html.Hidden("id", item.CategoryId)
<input type="submit" value="Delete" />
}
</td>
and created an action method like this:
[HttpPost]
public ActionResult Delete(int Id)
{
Category category = repository.Categories().FirstOrDefault(c => c.CategoryId == Id);
if (category != null)
{
repository.DeleteCategory(category);
TempData["message"] = string.Format("{0} was deleted", category.CategoryName);
}
return RedirectToAction("Categories");
}
It works fine. but I want to use hyperlink for delete as I am using for edit and details. How can I replace the button with actuionlink. I tried that but it is not going in delete post action link and I am getting view not found error.
You can make it look like a link instead of a button ussing css, something like this.
<input type="submit" value="delete" style="border: none; background: none;
text-decoration: underline;
cursor: pointer;">
Be careful not to make your Delete actions available via an HTTP GET. The HTTP spec recommends that HTTP POST is used for destructive actions (like a delete.) This prevents web crawlers from executing them.
By default hyperlinks issue HTTP GET. If you change your Delete action to a hyperlink make sure you override its behavior (via JavaScript) to issue a HTTP POST. Then you need to consider what happens if the browser has JavaScript turned off.
Another approach that you might want to consider is to [[make your Delete button look like a hyperlink via CSS styles[1]].
[1] http://www.xlevel.org.uk/post/How-to-style-a-HTML-Form-button-as-a-Hyperlink-using-CSS.aspx

Resources