Posting input text from form view to controller MVC - c#

So I have a form on my shared layout page that I want to simply post a text string to. I currently have a breakpoint sitting at the beginning of that action in the controller to test the form is working but it appears that it never gets there because it never hits the breakpoint. Here is my code anyone know what I am doing wrong?
View:
<form action="/RespondentSearch/Search" method="post" class="sidebarSearch">
<input type="text" name="search" placeholder="respondent search..." id="ac" class="ui-autocomplete-input" autocomplete="off" /><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
<input type="submit" value="" href="#moadalSearch" rel="lightbox" />
</form>
Controller:
public class RespondentSearchController : Controller
{
[HttpPost]
public ActionResult Search(string search)
{
string stuff = search;
return View();
}
}
My Visual Studio Debug Console though reads like there is an exception?
Following route: {controller}/{action}/{id} for request: http://localhost:56554/RespondentSearch/Search
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
Following route: {controller}/{action}/{id} for request: http://localhost:56554/Home/Login
Following route: {controller}/{action}/{id} for request: http://localhost:56554/
My Developer Tools Browser Debug:
Request URL:http://localhost:56554/RespondentSearch/Search
Request Method:POST
Status Code:302 Found
search:asdf <--- This is what I was typing in
It appears it is getting there but I am not hitting my breakpoint still? I also added a temp view for it to just output something when its there and still nothing. It is like it is completely avoiding my controllers action.

Related

How can I pass a value from input box to default Edit controller GET method, i.e. allow search box to show Edit view for a single record?

.NET Core v6
MVC Web App with Entity Framework Core
I scaffolded a database table and it created a "db context", then I scaffolded default Controller and Views.
On the home page, I want to create a search box where you put in the primary key, or id. On submit, I want the value passed to the default Edit controller. Essentially, I want someone to be able to pull up a single record to Edit, if they know the primary key (id).
Here is what I have for a search box
<form asp-controller="MyTables" asp-action="Edit">
<p>
PIN: <input type="text" name="id" />
<input type="submit" value="Find" />
</p>
</form>
Here is the default Edit method inside the Controller.
// GET: MyTables/Edit/XYZ
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}
var MyTable = await _context.MyTables.FindAsync(id);
if (MyTable == null)
{
return NotFound();
}
return View(MyTable);
}
When I run this, it doesn't work, but I don't know how to set it up. How can I make this work? The only way I've been able to pull a record is by adding method="get" to the form, but then it creates a URL structure using "id" as a parameter like this localhost/MyController/Edit?id=XYZ. This structure won't work because I'm unable to save the record when I've navigated to the page in this way.
I appreciate any pointers or ideas.
Thank you
EDIT AFTER COMMENTS:
It has been suggested that I could go ahead and use the method="get", thereby selecting the correct record. The URL would be in this format: localhost/MyController/Edit?id=XYZ. A proposed solution is to fix my POST action to be able to save the record when using such URL paths. I'm not sure why, but it will only save right now if the URL path is in this format: localhost/MyController/Edit/XYZ (no parameter ?id =).
Here is a version of my default POST Edit action in the controller.
// POST: MyTables/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("...,...,...,...,...,...,PrimaryKeyField")] MyTable myTable)
{
if (id != myTable.PrimaryKeyField)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(myTable);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MyTableExists(myTable.primaryKeyField))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(MyTable);
}
In the Edit view, to initiate the POST action, here's some of the Edit Form markup:
#model myApp.Models.MyTable
...
<form asp-action="Edit">
...
<div class="form-group">
<label asp-for="PrimaryKeyField" class="control-label"></label>
<input asp-for="PrimaryKeyField" class="form-control" />
<span asp-validation-for="PrimaryKeyField" class="text-danger"></span>
</div>
...
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
The reason I'm saying it won't Save is when I click Submit on the Edit form, it brings up this HTTP error:
This localhost page can’t be found. No webpage was found for the web address: https://localhost:7020/MyTables/Edit
HTTP ERROR 404
In the Edit View, I added a reference to the Model.
#model myApp.Models.MyTable
In the form, I added a Tag Helper.
<form asp-action="Edit" asp-route-id=#Model.PrimaryKeyField>
This is working.
I noticed in the URL pattern of /Edit/XYZ, the form's asp-action uses this pattern. I noticed with the URL pattern of /Edit/?id=XYZ, the form's action uses /Edit with NO ID. Therefore, I figured out a way to add the id to the form's action by using the asp-route-id tag helper. The form submits the data properly now.

How to post to the controller?

I am trying to post data from web form to the controller in my asp.net application so that I can authenticate the credentials which the user has enterted.
My code for the web form looks like this at the bottom of this code there is a submit button.
<form action="~/Controller" method="post">
<fieldset>
<legend> Enter your details</legend>
<div>
<label for="name ">name </label>
<input type="text" name="name" value=""/>
When I run the code and then press the submit button I get an error 405 which is because a HTTP method is not allowed. This is code I have in the controller file. Is the error because I have made a mistake in the web forms of its it because of a error in the controller file.
[HttpPost]
public void MyAction(string telephone, string emailadress, string name )
{
}
You can use tag-helpers, like seen below. documentation: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-5.0
<form asp-controller="Home" asp-action="MyAction" method="post">
<!-- Input and Submit elements -->
</form>

StackOverflow Exception from subbmitting a simple form MVC ASP.Net Website

I'm trying to submit a simple form for my ASP.NET MVC website, but I keep getting a StackOverFlow Exception. I don't understand what I'm doing wrong; it should be a pretty straightforward process...
Here is the form code:
<form action="/Home/SubmitAnnouncements" method="post">
<textarea name="announcementcode" style="width:100%; height:800px">#Model.RawAnnouncementCode</textarea>
<div id="find_account" class="two columns"><input id="find_account_btn" class="link_button" type="submit" name="Submit" value="Submit New Announcements" /></div>
</form>
And here is the Controller code for the action:
[HttpPost, ValidateInput(false)]
public ActionResult SubmitAnnouncements(string announcementcode)
{
SubmitAnnouncements(announcementcode);
return RedirectToAction("Index", "Home");
}
This problem stated when I added [HttpPst, ValidateInput(false)], but I need to do that, because the user is submitting raw HTML code. Any ideas anyone?
The ValidateInput attribute didn't cause your error, you just never reached the point in your code that causes the StackOverflowException until it was added.
If you look at the first line of your action, you'll notice you're calling the same method.

View Could Not Be Found

In a ASP.NET MVC website; does every view need to have a corresponding/associated Model and Controller?
I am building the bare bones of my website; so I have created all the views but not the Models or Controllers yet. I want to be able to view a page (that contains no content associated with a model or any functionality that a controller should handle - yet). So at this point every view (cshtml page) is a static HTML page.
But when I go to access any view/page I get the error:
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: /TeamMember/raiseIssue
raiseIssue.cshtml content:
#{
Layout = "layouts/main.cshtml";
}
<form action="#ViewBag.PostUrl" method="post">
<div class="row feedback-input text-center">
<textarea name="Text"></textarea>
</div>
<div class="row text-center">
<button type="submit" class="btn btn-default btn-standard">Submit</button>
</div>
</form>
MVC do not allows to browse the view directly. What you can do is create empty controller method like below
public ActionResult RaiseIssue()
{
return View();
}
in controller TeamMemberController
One other thing, please make sure that proper route are configured in RouteConfig.cs
I hope using this method you will be able to browser the view with writing much code in controller or model/

button event not working

I want this:
#using (Html.BeginForm("bgcTest", "CompaniesController"))
{
<p>
Ange BolagsID: <br />
<input type="text" name="BolagsID" />
<input type="submit" value="bgc test" />
</p>
}
To fire this event:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult bgcTest(string BolagsID)
{
...
}
But I get the error:
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: /CompaniesController/bgcTest
I can't for the life of me figure it out. If I just make an actionlink I get my method to fire, but I need an user inputted variable to go along with the fireing.
What am I doing wrong?
(This is my first time with MVC and I have to implement some functionality into an already existing project. For work.)
The name of your controller class (.cs file) is CompaniesController.cs.
That's a convention (default behavior) where MVC will automatically identify it as a controller.
When referencing this controller in your view, use Companies only.
If you use CompaniesController MVC will try to find a CS file named CompaniesControllerController.
Correct code:
#using (Html.BeginForm("bgcTest", "Companies"))

Categories