ASP.NET MVC form\controller routing issue - asp.net-mvc

I'm a bit new to MVC and have no idea why following issue happening.
According to tutorial we can handle form posts by this code:
View:
<form action = "/learning/Goto" method="GET">
<input type="text"name="gotoUrl"/>
<input type="submit" name="Goto"/>
</form>
where Learning is Controller and goto is method as I understood.
Controller:
public ActionResult Goto(string gotoUrl)
{
return Redirect(gotoUrl);
}
I have a question: all I did according to the tutorial video and it worked in the video. However I have some trouble.
In my view I have warning:
"Path E:\Programming\MVC_Learning\learning not found" in the following line:
<form action = "/learning/Goto" method="GET">
I think that need to setup path to Controller folder. But what I don't understand the most the fact that it works and really redirect to input address but only in this form: "http:// mysite.net". If I write mysite.net I get exception
HTTP Error 404.0 - Not Found
Requested URL
http://localhost:64074/learning/mysite.net
Physical Path E:\Programming\C_SHARP\MVC_Learning\MVC_Learning\learning\mysite.net
So could somebody explain me following:
1. Why it works with http but does not work without?
2. Why I get warning on
<form action = "/learning/Goto" method="GET">
?

Your controller action url wrong, Instead of "/learning/Goto" use(Most Preferred way in MVC)
<form action = "#Url.Action("Goto","learning")" method="GET">
or just remove "/" and
<form action = "learning/Goto" method="GET">

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
});
}

Http.BeginForm does not post

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.

.Net MVC form post failing on server

I created a simple form that works fine when I run it in Visual Studio, but fails on my website with a 404 error.
I have an Action set up to receive only "post" messages using [HttpPost].
If I change the Acton to receive "get" messages, the Action is called, but the form information is not passed along.
This site is written with .Net MVC, could there be some kind of security or something on the server that may need to be changed to allow for "post" calls?
Controller Code -
[HttpGet]
public ActionResult Tester1()
{
return View("Tester1");
}
[HttpPost]
public ActionResult Tester2(MyModel myModel)
{
return View("Tester2", myModel);
}
Tester1.cshtml Code -
#model FS.Models.MyModel
#using (Html.BeginForm("Tester2", "Comics", FormMethod.Post))
{
<div>
Enter Text -
#Html.TextBoxFor(m => m.property1)
</div>
<div>
<input type="submit" value="SEND!" />
</div>
}
Tester2.cshtml Code -
#model FS.Models.MyModel
You entered - #Model.property1
Global.asax.cs Code -
routes.MapRoute(
"Tester2Route", // Route name
"{controller}/Tester2", // URL with parameters
new { controller = "Comics", action = "Tester2" } // Parameter defaults
);
(the code above is just a summarized version, you can visit the actual site here - http://funkysmell.com/Comics/Tester1/)
I was able to get this to work.
The problem is that the server you are running on is wanting a trailing slash (/) after the URL. So when I looked at your example, the URL generated is
<form action="/Comics/Tester2" method="post">
If you add a trailing slash it will work. i.e.
<form action="/Comics/Tester2/" method="post">
Take a look here to get more information.
Why is ASP.NET MVC ignoring my trailing slash?
There are links in that answer to a few blogs which should help you out.

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,

Internet Explorer Post Data Bug - ASP.NET MVC

I just started playing with MVC and I've run into a roadblock. I'm using a partial view as a User Login flyout on the header of each page using OpenID. When the user clicks on the provider (similar to stackoverflow) it authenticates and then either returns to the calling page or redirects to the signup page. The code works flawlessly under Firefox and Chrome but bombs out in IE. The "provider" parameter in the controller is always sent as null. Is there some sort of bug involving posting input names/values in IE or am I doing something wrong?
This is what my openid partial view looks like:
<% using (Html.BeginForm("Authenticate", "Membership", new { ReturnUrl = Request.Url }, FormMethod.Post))
{
if (!Page.User.Identity.IsAuthenticated)
{ %>
<div class="openidProviders">
Log in or join using one of these OpenID providers:
<div class="large buttons">
<div class="provider"><div><%= Html.SubmitImage("provider", "/Content/common/images/google.gif", new { value = "Google" })%></div></div>
<div class="provider"><div><%= Html.SubmitImage("provider", "/Content/common/images/Yahoo.gif", new { value = "Yahoo" })%></div></div>
<div class="provider"><div><%= Html.SubmitImage("provider", "/Content/common/images/AOL.gif", new { value = "AOL" })%></div></div>
<div class="provider"><div><%= Html.SubmitImage("provider", "/Content/common/images/OpenId.gif", new { value = "OpenId" })%></div></div>
</div>
</div>
<% }
}
%>
And the controller logic is here:
[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public void Authenticate(string provider, string ReturnUrl)
{
// Figure out provider endpoint
// Authentication function calls here
}
Well, it looks like IE, for once, is the only browser properly following the HTML spec according to this post.
The HTML specification only requires
that x, y coordinates where the image
submit button was clicked be sent to
the web server. IE follows the
specification. The browsers that send
the value="..." parameter are doing
their own thing outside of the HTML
specification.
Basically, I need to use a submit input instead of SubmitImage and then style the background of the button accordingly. Not the optimal solution but at least it works. This is what the final solution looks like. If anyone knows a way of getting the SubmitImage to work properly, let me know.
Replace the buttons above with ones that look like this:
<input type="submit" value="Google" class="google_OpenID" name="provider" />
And the CSS class:
.google_OpenID
{
background-image: url(/Content/common/images/google.gif);
width:75px;
cursor:pointer;
color:transparent;
height:35px;
border:none;
}

Resources