Bad Request MVC HttpPost - asp.net-mvc

I have the following cshtml file.
#model Models.AuthorizeUser
#{
ViewBag.Title = "Authorize";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="card card-container">
<img class="profile-img-card" src="~/Content/images/rblogo_reverse-pms348_000.gif" />
<p> </p>
<form method="POST">
<p>Hello, #Model.Name</p>
<p>A third party application want to do the following on your behalf:</p>
<ul>
#foreach (var scope in Model.Scopes)
{
<li>#scope.ScopeDescription</li>
}
</ul>
<div class ="row">
<div class="col-md-4">
<button class="btn btn-block btn-primary btn-signin" name="submit" type="submit" value="authorize">Grant</button>
</div>
<div class="col-md-8">
<button class="btn btn-block btn-primary btn-signin btn-small-text" name="submit" type="submit" value="logout">Sign in as different user</button>
</div>
</div>
</form>
</div>
</div>
I have my controller file as follows:
public class OAuthController : Controller
{
[HttpGet]
public ActionResult Authorize()
{
logger.Trace("Authorize method entered");
AuthorizeUser authorizeUser;
......
return View(authorizeUser);
}
[HttpPost]
public ActionResult Authorize(AuthorizeUser authorizeUser, string submit)
{
logger.Trace("Authorize with object");
if (Response.StatusCode != 200)
{
logger.Trace("status code " + Response.StatusCode);
logger.Trace("status description " + Response.StatusDescription);
return View("AuthorizeError");
}
..............
}
When the form is displayed, the info is displayed correctly. After I click Grant button, I got Response.StatusCode == 400. Both authorizeUser and submit are null. I am expecting StatuCode == 200 with values of authrizeUser and submit.

Have you tried using Html.BeginForm()?
Instead of using <form method="POST"> you could use Html.BeginForm("Action", "Controller")

Related

Edit action has not been hitting while I push the submit button

I have an edit button in each row of my Datatable. I have two actions for editing. One for Getting data in a Datatable and the other one for posting my information. The code behind my Edit button in the my Home Index is:
{
"data": "Id",
"render": function (data, type, full, meta) {
return `<div class="text-center"> <a class="btn btn-info"
href="/Home/EditGet/` + data + `" >Edit</a> </div> `;
}
and my home controller methods are:
/// Get Edit
[HttpGet]
[Route("{Id}")]
public IActionResult EditGet(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
var obj = _sv.OpenRecord(id);
if (obj == null)
{
return NotFound();
}
return View("EditGet", obj);
}
/// Post Edit
[HttpPost]
public IActionResult EditPost(SalesVeiwModel sales)
{
if (ModelState.IsValid)
{
var res= _sv.Update(sales.Comment);
if (res==null )
{
return Json(data: "Not found");
}
return RedirectToAction("EditGet");
}
return Json(data: "Is not valid");
}
And finally my EditGet view is like bellow:
<form id="contact-form" method="post" asp-controller="Home" asp-
action="EditPost" role="form" >
<input asp-for="Id" hidden />
<div class="form-group">
<label>Invoice Nomber</label>
<input id="form_IBNo" type="text" class="form-control" disabled asp-for="IBNo">
</div>
.
.
.
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Confirm" asp-
controller="Home" asp-action="EditGet">
</form>
You should have two buttons,one call EditGet,one call EditPost,here is a demo:
<form id="contact-form" method="post" asp-controller="Home" asp-
action="EditPost" role="form" >
<input asp-for="Id" hidden />
<div class="form-group">
<label>Invoice Nomber</label>
<input id="form_IBNo" type="text" class="form-control" disabled asp-for="IBNo">
</div>
.
.
.
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Confirm">
<a class="btn btn-success btn-send" value="Confirm" asp-controller="Home" asp-action="EditGet" asp-route-id="1">EditGet</a>
</div>
</form>

Edit action in controller not updating

When I edit an item and return to the index view the item doesn't show what I updated it to.
I think I know what the problem is but not sure how to fix it. In my service class I have a CreateEditItem method and when I step thru the code it hits the if condition <=0. So it acts like there is an id of 0 when I click the submit button to submit my update. I'm not sure what to do to fix this. Do I need to have a separate method for Edit? And if so what should that look like?
public bool CreateEditItem(Item item)
{
if (item.ItemId <= 0)
{
var maxId = _mockList.Max(p => p.ItemId);
item.ItemId = maxId + 1;
_mockList.Add(item);
return true;
}
var itemToEdit = _mockList.FirstOrDefault(p => p.ItemId ==
item.ItemId);
itemToEdit = item;
return true;
}
Action in Controller
[HttpPost]
public IActionResult EditItem(Item itemToEdit)
{
_itemService.CreateEditItem(itemToEdit);
return RedirectToAction(nameof(Index), new { id =
itemToEdit.ItemId });
}
View:
<div class="row">
<form asp-action="EditItem">
<div asp-validation-summary="ModelOnly" class="text-
danger"></div>
<div class="container form-group">
<div class="row">
<div class="col-md-2">As Of : <label
for="AsOf" /></div>
<div class="col-md-4"><input id="AsOf"
value="#Model.ItemToEdit.AsOf" name="AsOf" type="date" /></div>
</div>
<br />
<div class="row">
<div class="col-md-2">Title Summary : <label
for="TitleSummary" /></div>
<div class="col-md-2"><input id="TitleSummary"
value="#Model.ItemToEdit.Title" name="Title" type="text" /></div>
</div>
<br />
<br />
<div class="row">
<div class="col-md-2"><input type="submit"
value="Submit" class="btn btn-primary" /></div>
</div>
</div>
</form>
</div>
I expect when I click the submit button to submit my update it will show the updated Title and/or AsOf date.
change your method from HTTPut to HttpPost
it will work.

Delete Action does not activate/trigger ASP.NET Core MVC

HttpPost on delete action does not trigger, however HttpGet seems working fine as i get the content displayed. However I have little confusion in the following route address generated when I click on HttpGet on delete action:-
https://localhost:44394/9
shouldn't it generates link like this: https://localhost:44394/Post/DeletePost/9
Controller:-
[HttpPost, ActionName("DeletePost")]
public async Task<IActionResult> ConfirmDelete(int id)
{
await _repository.DeletePostAsync(id);
return RedirectToAction(nameof(GetAllPosts));
}
[HttpGet("{id}")]
public async Task<IActionResult> DeletePost(int id)
{
var post = await _repository.GetPostById(id);
if(post == null)
{
return NotFound();
}
return View(post);
}
Razor View for HttpGet:-
<div class="btn btn-outline-danger delete">
<a href="#Url.Action("DeletePost", "Post", new { id = p.Id })">Delete
</a>
</div>
Razor Page HttpPost:-
<div class="container">
<div class="row">
<div class="col-9">
<p>
#Model.Topic
</p>
<p class="timeStampValue" data-value="#Model.Published">
#Model.Published
</p>
<p>
#Model.Author
</p>
<section>
<markdown markdown="#Model.Content" />
</section>
</div>
</div>
<form asp-action="DeletePostAsync">
<input type="hidden" asp-for="Id" />
<button type="submit" class="btn btn-outline-danger">Delete</button>
</form>
Cancel
</div>
Routing:-
app.UseMvc(routes =>
{ routes.MapRoute(
name: "KtsPost",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Post", action = "Index" },
constraints: new { id = "[0-9]+" });
});
Your action name is wrong in the form. Your code should be instead:
<form asp-action="DeletePost">
<input type="hidden" asp-for="Id" />
<button type="submit" class="btn btn-outline-danger">Delete</button>
</form>
The default method of an HTML form is GET not POST. You need to tell your form to POST. Also, the action name should be ConfirmDelete:
<form asp-action="ConfirmDelete" method="post">
<input type="hidden" asp-for="Id" />
<button type="submit" class="btn btn-outline-danger">Delete</button>
</form>

How do I redirect from an MVC Post Action back to the bootstrap popup modal partial view where the post came from?

How do I redirect from an MVC Post Action back to the bootstrap popup modal partial view where the post came from?
Here is the PartialView sitting in the Bootstrap modal popup on the page.
It has a div with a validation taghelper waiting for any model errors.
#model CreateRoleViewModel
<div class="panel panel-primary partialModalFormDivs">
#Html.Partial("_ModalHeader",
new ModalHeader
{
Heading = "ADD ROLE",
glyphiconClass = "glyphicon glyphicon-random"
}
)
<div class="panel-body">
<div asp-validation-summary="All" class="text-danger"></div>
<form asp-action="CreateRole" method="post">
<div class="form-group">
<label asp-for="RoleName"></label>
<input asp-for="RoleName" class="form form-control" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Create</button>
<a asp-action="Index" class="btn btn-default">Cancel</a>
</div>
</form>
</div>
</div>
It posts to this action:
[HttpPost]
public async Task<IActionResult> CreateRole(CreateRoleViewModel createRoleViewModel)
{
if (ModelState.IsValid)
{
IdentityRole role = new IdentityRole(createRoleViewModel.RoleName);
IdentityResult result
= await _roleManager.CreateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
foreach (IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
}
return View(createRoleViewModel);
}
I can return a PartialView like this at the end:
return View("_CreateRole", createRoleViewModel);
But then the whole page is cleared and this partial is returned with no layout file.
How can I return the results back to the modal popup window.
I understand the problem and the current behavior. But has anyone else solved this?
I think what you want to do is an ajax post and then just return a partial view and replace the form. The form should be inside a container div with an id that is used to replace its contents with the ajax post result. To do this you need to include the jquery unobtrusive ajax script which will auto wire the ajax based on the data-* attributes on the form as shown below
<div class="panel-body">
<div asp-validation-summary="All" class="text-danger"></div>
<div id="resultcontainer">
<form asp-action="CreateRole" method="post"
data-ajax="true"
data-ajax-method="POST"
data-ajax-mode="replace"
data-ajax-update="#resultcontainer"
>
<div class="form-group">
<label asp-for="RoleName"></label>
<input asp-for="RoleName" class="form form-control" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Create</button>
<a asp-action="Index" class="btn btn-default">Cancel</a>
</div>
</form>
</div>
</div>
and don't forget to return a partial view
return PartialView(createRoleViewModel);

Validation multiple checkbox form

in the page I have only three checkbox, the client should choose at least one before clicking on the submit button :
Controller :
[HttpPost]
public ActionResult Client(OrderItems model)
{
if (bValidated){
//Code here
}
else
{
model.itemChoosed = false;
return View("Client", model);
}
View Client :
#model WebApp.Models.OrderItems
#using (Html.BeginForm("Client", "Home", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
#Html.AntiForgeryToken();
<h2>Client</h2>
#Html.Partial("SentMessage")
<div>
<div>
<h3>Item 1</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item1) Item 1</label>
</div>
<div>
<h3>Item 2</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item2) Item 2</label>
</div>
<div>
<h3>Item 3</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item3) Item 3</label>
</div>
</div>
<div class="row">
<input type="submit" name="action:Client" id="btnClient" class="btn btn-primary flat btn-large pull-right" value="Client" />
</div>
}
After I choose to put the condition into a Partail View :
Partial View SentMessage:
#model WebApp.Models.OrderItems
#if (!model.itemChoosed)
{
<div>You must choose at least one item</div>
}
I have the error message :
The view 'Client' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Client.aspx
..
~/Views/Home/Client.cshtml
..
but Home/Client.cshtml existe since it's the view
Thanks

Resources