Adding two buttons to a form asp.net mvc5? - asp.net-mvc

I am trying to add two buttons to my page, an "Accept" button and a "Reject" button. I have done like so
<button type="submit" name="SubmitButton" value="Accept" class="btn btn-sm btn-success">Accept</button>
<button type="submit" name="SubmitButton" value="Reject" class="btn btn-sm btn-danger">Reject</button>
Then in my controller I have the following
public ActionResult ViewRequest(string SubmitButton, int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
RequestLift requestLifts = db.requestLifts.Find(id);
if (requestLifts == null)
{
return HttpNotFound();
}
Lift lifts = db.Lifts.Find(id);
if (SubmitButton == "Accept")
{
requestLifts.bookingStatus = "Accepted";
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else if (SubmitButton == "Reject")
{
requestLifts.bookingStatus = "Rejected";
db.SaveChanges();t request has been rejected";
return RedirectToAction("Index", "Home");
}
return View(requestLifts);
}
However nothing happens on the button click?
#Html.BeginForm("ViewRequest", "SubmitButton")
{
<button type="submit" name="SubmitButton" value="Accept" class="btn btn-sm btn-success">Accept</button>
<button type="submit" name="SubmitButton" value="Reject" class="btn btn-sm btn-danger">Reject</button>
}

You need to wrap Html.BeginForm with using. This determines how the opening and closing form tags get added, i.e. around the buttons within the form. Your problem with submitting is that these buttons are not currently actually within your form tag.
#using (Html.BeginForm("ViewRequest", "SubmitButton"))
{
<button type="submit" name="SubmitButton" value="Accept" class="btn btn-sm btn-success">Accept</button>
<button type="submit" name="SubmitButton" value="Reject" class="btn btn-sm btn-danger">Reject</button>
}

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>

ASP.NET MVC Show message before redirects if success

Here's my web api on account controller using identity that can change the password wit validation using data annotations
[HttpGet]
[AllowAnonymous]
public IActionResult ChangePassword(string email, string returnUrl)
{
return email == null || returnUrl == null ? View("Error") : View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (model == null)
{
return BadRequest();
}
if (ModelState.IsValid)
{
var result = await _changePasswordCommand.ChangePassword(model);
if (result.Succeeded)
{
ViewBag.IsSuccess = true;
ModelState.Clear();
return Redirect(model.returnUrl);
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View(model) ;
}
then in my div razor views
<form class="change-password-form" asp-controller="Account" asp-action="ChangePassword" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input id="email-hidden" asp-for="Email" type="hidden" />
<input id="return-url" asp-for="ReturnUrl" type="hidden" />
<div class="form-group change-password">
#if (ViewBag.IsSuccess == true)
{
<div class="alert alert-success alert-dismissible fade show text-center">Successfully Changed Password!</div>
}
<label asp-for="CurrentPassword" class="control-label"></label>
<input class="form-control" type="password" asp-for="CurrentPassword">
<span asp-validation-for="CurrentPassword" class="text-danger"></span>
</div>
<div class="form-group change-password">
<label asp-for="NewPassword" class="control-label">New password</label>
<input id="password" class="form-control" type="password" name="newPassword" asp-for="NewPassword" onkeyup="isGood(this.value)">
<span asp-validation-for="NewPassword" class="text-danger"></span>
</div>
<div class="form-group change-password">
<label asp-for="ConfirmNewPassword" class="control-label"></label>
<input asp-for="ConfirmNewPassword" class="form-control" type="password" />
<span asp-validation-for="ConfirmNewPassword" class="text-danger"></span>
</div>
<div class="change-password-footer">
<button id="btn-cancel" type="button" class="btn btn-primary cancel">
CANCEL
</button>
<button id="btn-save" type="submit" class="btn btn-secondary save" disabled>
SAVE
</button>
</div>
</form>
I want to be able to show the successfully changed password message before it redirects problem is it always redirect to account/changepassword after submit
You can write if condition outside the form tag, like this
#if (ViewBag.IsSuccess == true)
{
<div class="alert alert-success alert-dismissible fade show text-center">Successfully
Changed Password!
</div>
}
<form class="change-password-form" asp-controller="Account" asp-action="ChangePassword" method="post">
#*your code*#
</form>
Or remove method="post" then try
look at this place in your account controller.
...
if (result.Succeeded)
{
ViewBag.IsSuccess = true;
ModelState.Clear();
return Redirect(model.returnUrl);
}
...
Instead of the re-direct, use "return View(model);". then you can redirect the page ajax, (testing if the ViewBag.IsSuccess == true and model.returnUrl != null) you in the account controller, you will instead have.
...
if (result.Succeeded)
{
ViewBag.IsSuccess = true;
ModelState.Clear();
//return Redirect(model.returnUrl);
return View(model);
}
...
With this, the success alert would show. Then have a javascript method onload, test if success is true and the the return is not null. something like this (in the view)
...
#{
bool isSuccess = ViewBag.IsSuccess;
string rUrl = model.returnUrl;
}
...
<script>
function redirect(isSuccess, returnUrl)
{
//use ajax to redirect;
}
redirect(#isSuccess, #rUrl);
</script>

Blazor how to add/remove class on only one element with same class not all of them

I'm new to blazor I have 2 (or more) elements with same class booksMain I want to make them disappear on click. How I could add class on click or css but I want to add only on the one clicked not all booksMain-s
Is it possible without JS Interop
and
Another example
<button class="btn btn-success" #onclick="ChangeColor">Click Me1</button>
<button class="btn btn-success" #onclick="ChangeColor">Click Me1</button>
<button class="btn btn-success" #onclick="ChangeColor">Click Me1</button>
<button class="btn btn-success" #onclick="ChangeColor">Click Me1</button>
<button class="btn btn-success" #onclick="ChangeColor">Click Me1</button>
How to make this work?
#page "/"
#foreach (var item in items)
{
<button class="#item.Color" #onclick="#(() => item.Shown = !item.Shown )">#item.ID</button>
}
#code {
List<Book> items = Enumerable.Range(1, 10).Select(i => new Book { ID = i, Title=$"Title{i.ToString()}", Shown = false }).ToList();
public class Book
{
public int ID { get; set; }
public string Title { get; set; }
public bool Shown { get; set; }
public string Color => Shown ? "green" : string.Empty;
}
}
app.css or style.css
.green {
background-color: green;
}
Note: The above code is a simple toggling... now model your code accordingly.
Update as per request... Note that the above solution is much better than the following one:
#page "/"
<button type="button" class="#Color[0] btn btn-success" #onclick="#(() => ChangeColor(0))">Click Me1</button>
<button type="button" class="#Color[1] btn btn-success" #onclick="#(() => ChangeColor(1))">Click Me1</button>
<button type="button" class="#Color[2] btn btn-success" #onclick="#(() => ChangeColor(2))">Click Me1</button>
<button type="button" class="#Color[3] btn btn-success" #onclick="#(() => ChangeColor(3))">Click Me1</button>
<button type="button" class="#Color[4] btn btn-success" #onclick="#(() => ChangeColor(4))">Click Me1</button>
#code {
string []Color = new String[] {"", "", "", "", "" };
private void ChangeColor(int index)
{
if (Color[index] == "")
{
Color[index] = "blue";
}
else
{
Color[index] = "";
}
}
}
app.css or style.css
.blue {
background-color: blue;
}
Hope this helps..

identify which button is being clicked in mvc 5

I am creating a web app using mvc 5 here i have two buttons
<div class="row">
<div class="col-sm-offset-5 col-sm-1">
<input type="submit" name="save" value="SAVE" class="btn btn-primary glyphicon glyphicon-save" />
</div>
<div class="col-sm-offset-0 col-sm-1">
<input type="submit" name="reset" id="reset" value="Reset" class="btn btn-warning active glyphicon glyphicon-refresh" />
</div>
</div>
and i have a method which is being called after button click,
now on that event i want to differentiate the button click,
like,
if a user click
<input type="submit" name="save" value="SAVE" class="btn btn-primary glyphicon glyphicon-save" />
then
{
//this code should run
}
and if a user clicks
<input type="submit" name="reset" id="reset" value="Reset" class="btn btn-warning active glyphicon glyphicon-refresh" />
then
{ //this set of code should run }
and my method looks like this
[HttpPost]
public ActionResult insertrecd(FormCollection fc)
{
if(fc["reset"]==null)
{
return RedirectToAction("party", "party");
}
else
{
ViewBag.message = string.Format("Hello {0}.\\nCurrent Date and Time: {1}", "name", DateTime.Now.ToString());
return RedirectToAction("party", "party");
}
}
what i need to do, i want to do different code on different button clicks?
Give each input button the same name, but a different value
<input type="submit" name="action" value="save" class="btn btn-primary glyphicon glyphicon-save" />
<input type="submit" name="action" id="reset" value="reset" class="btn btn-warning active glyphicon glyphicon-refresh" />
The value will then be in your form collection as
fc["action"]
So your controller action could look like
[HttpPost]
public ActionResult insertrecd(FormCollection fc)
{
var action = fc["action"];
if(action == "save")
{
//save stuff
}
if(action =="reset")
{
//reset stuff
}
}

ASP.NET MVC - change button name in the same view

How can I change button name in a same view, my view is "_CreateOrUpdate", I want to call Save Action my button name change is Save and else when I call Update Action my button change Update.
<div class="form-actions">
<button type="submit" class="btn btn-primary" value="Save"><i class="icon-save"></i>Save</button>
You can have a property in the model for the button text.
#using (Html.BeginForm())
{
<button type="submit" class="btn btn-primary" value="Save"><i class="icon-save"></i>#Model.ButtonName</button>
}
Demo
this is solution for my answer.
#if (ViewContext.RouteData.GetRequiredString("action") == "Create")
{
<button type="submit" class="btn btn-primary" value="Save"><i class="icon-save"></i> Save</button>
}
else
{
<button type="submit" class="btn btn-primary" value="Edit"><i class="icon-save"></i> Save changes</button>
}
You can use simple JS function for this which will change button value. When the page is ready:
var button = document.getElementById("saveButton");
button.value = [Basically anything you want to pass from controller];
Another option is to use razor and ViewBag to pass something from controller. This is easier if you want just to pass Save/Update from controller:
ViewBag.CreateUpdate = "Save";
and in the view:
<button type="submit" class="btn btn-primary"><i class="icon-save"></i>#ViewBag.CreateUpdate</button>

Resources