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
Related
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
});
}
I am trying to create a form in a view and am running into trouble with the routing; it seems to be totally ignoring the action name that I am providing. Here are my controller methods (Controller is called "MyController"):
[HttpGet]
public ActionResult CreateNewRequest()
{
if (ModelState.IsValid)
{
MyViewModelClass model = new MyViewModelClass();
return View("CreateNewRequest", model);
}
else
{
return DisplayModelStateError(ModelState.Values);
}
}
[HttpPost]
public ActionResult CreateNewRequest(MyViewModelClass model)
{
//code to process the view model
return RedirectToAction("Index");
}
In my view, I have tried several variations of the same thing to render a form, including:
#using (Html.BeginForm("CreateNewRequest","My",FormMethod.Post))
#using (Html.BeginForm("CreateNewRequest","My"))
#using (Html.BeginForm("CreateNewRequest","My",null,FormMethod.Post))
They all fail when the user clicks the submit button; I get an error that says:
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: /My
What is especially odd is that if i reverse them (which I know to be incorrect), I get an error message implying it looked for the action as opposed to totally ignoring it. For example, if I try
#using (Html.BeginForm("My","CreateNewRequest",FormMethod.Post))
I get the following error message:
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: /CreateNewRequest/My
Any ideas here?
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.
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.
Ive been working on converting a MVC4 project over to MVC5. The first day I ran into an 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' but was able to resolve it by starting my conversion over. I'm not sure what the fix was which is a bummer, because its happened again.
The Error occurs in _ExternalLoginsListPartial.cshtml when I load the Login.cshtml page. The error is thrown on line 15. (string action = Model.Action;)
#using Microsoft.Owin.Security
#{
var loginProviders = Context.GetOwinContext().Authentication.GetExternalAuthenticationTypes();
var authenticationDescriptions = loginProviders as AuthenticationDescription[] ?? loginProviders.ToArray();
if (!authenticationDescriptions.Any())
{
<div>
<p>There are no external authentication services configured. See this article
for details on setting up this ASP.NET application to support logging in via external services.</p>
</div>
}
else
{
string action = Model.Action;
string returnUrl = Model.ReturnUrl;
using (Html.BeginForm(action, "Account", new { ReturnUrl = returnUrl }))
{
#Html.AntiForgeryToken()
<div id="socialLoginList">
<p>
#foreach (AuthenticationDescription p in authenticationDescriptions)
{
<button type="submit" class="btn btn-default padded-8 margin-8" id="#p.AuthenticationType" name="provider"
value="#p.AuthenticationType" title="Log in using your #p.Caption account">
<img src="#Url.Content("~/Content/Brands/"+p.Caption+".png")" alt="Microsoft" class="img-responsive" />
<br/>
<b>#p.Caption</b>
</button>
}
</p>
</div>
}
}
}
The error thrown is
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'object' does not contain a definition for 'Action'
The snapshot says
Message : object' does not contain a definition for 'Action'
Source : Anonymously Hosted DynamicMethods Assembly
Now this is double weird because when I set a breakpoint Model.Action is not null. I can see the value.
This is really frustrating. The app was working 5 min ago.. I had changed the html on a non related page.. and now it wont work.
Hackish Fix
I would rather know why this error is happening. That said, I have a quick fix in case anyone else comes across this (Because this is part of part of the default solution). The solution is to not use dynamics. Create your own viewmodel and pass that.
public class ExternalLoginViewModel
{
[Display(Name = "ReturnUrl")]
public string ReturnUrl { get; set; }
[Required]
[Display(Name = "Action")]
public string Action { get; set; }
}
#Html.Partial("_ExternalLoginsListPartial", new ExternalLoginViewModel { Action = "ExternalLogin", ReturnUrl = ViewBag.ReturnUrl })
Check the views in the Account folder and for each one that has an explicit model, make sure the (view)model is in the right namespace. Mouse over the m parameter (m => m.UserName ... etc) and make sure it is referencing the correct (view)model.
In my case, I moved AccountViewModels to a different folder and the app broke as above. It appears the views are sort of "caching" the model from the original namespace. I used a silly fix (commented out the #model line and un-commented it back). Got warning that m is dynamic but when built and ran it worked. Looks like a glitch in VS 2013 RTM.
This bug is verified by Microsoft, and they are working on fixing it.
So anyone from the future who reads this: try updating visual studio 2013 to at least update 2.
https://connect.microsoft.com/VisualStudio/feedback/details/813133/bug-in-mvc-5-framework-asp-net-identity-modules
Found a solution for my own (mvc5) project after some experimenting.
I had a _ExternalLoginsListShoppingCartPartial.cshtml (from my mvc4 project) with #model ICollection<AuthenticationClientData> at the top. I commented it out and rebuild the solution and suddenly it works. I'm not even using that partial view in any view so it's a pretty nasty bug imo.
So check in your project. You may have some mvc4/simplemembership stuff that is messing up your mvc5 project.
I got the same error after replacing account models to another folder. When I double checked each view under the Account folder I found out my "Manage.cshtml" referenced to old namespace. I changed it to correct namespace for my models and the error fixed.
For me I had changed the contents of the ManageUserViewModel to add a property... I then started getting the error. When I changed the Manage.cshtml from not using an explicit model to using:
#model XYZ.Models.ManageUserViewModel
and removed the using statements, it started working again. One hour wasted!
I also hit this issue with VS 2013 U3. I had just added an email field to RegisterViewModel with the [EmailAddress] attribute, and it was crashing when I tried visiting the Register page. Commenting out the [EmailAddress] attribute fixed the issue. However, it continued working after I added the attribute back in, so this is probably a broader issue that could have to do with changes to the model classes.
yeah, I replaced the "else" code with the following and its working but still trying to see why it didn't work when using Model.Action ?
//string action = Model.Action;
//string returnUrl = Model.ReturnUrl;
//using (Html.BeginForm(action, "Account", new { ReturnUrl = returnUrl }))
using (Html.BeginForm("ExternalLogin", "Account", new { ReturnUrl = ViewBag.ReturnUrl }))