How to use buttons in MVC for different purposes - asp.net-mvc-4

I do have three buttons in my view. So now I want two buttons to post back and the third button to perform some jquery. How to do this. Like how to make the third button not to post back and perform some jquery actions.
Thanks

You can do this like
<form id="myForm">
<%-- form data inputs here ---%>
<button id="Postback">Postback</button>
<button id="JavaScript">JavaScript</button>
</form>
and in javascript
<script type="text/javascript">
$("#Postback").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("action","MyController")");
form.submit();
});
$("#JavaScript").click(function() {
Do your javascript something.
});
</script>

In HTML the tag button has the attibute type:
To post back data (submit a form) you must set type to submit (this is default value, so you may drop the type attribute at all).
To perform some javascript actions you must set type to button.
In two different submit buttoms use same name and different values:
#using (Html.BeginForm("Login", "Home")
{
<label for="login">Login:</label>
#Html.TextBox("login", Model.Login)
<label for="password">Password:</label>
#Html.Password("password", "")
<button type="submit" name="what" value="login">Log in</button>
<button type="submit" name="what" value="register">Register</button>
<button type="button" id="facebook">Facebook authentication</button>
}
<script>
$(function() {
// Perform jquery action.
$('#facebook').click(...);
});
</script>
In controller:
public ActionResult Login(string login, string password, string what)
{
if (what == "login")
. . .
else if (what == "register")
return RedirectToAction("Register", "Home");
}

Related

Post form with a page handler after changing the value in Select input

I am rather new to .NET 6/Razor pages. I want to mimic the behavior of the web forms when the drop down list value was changed. In web form, I could do OnSelectedIndexChanged and it would hit a specific method in the code behind. What is the best way to do this with a razor page?
Currently, I have
<button class="btn btn-info text-white" asp-page-handler="ResetForm"><i class="fa-solid fa-ban"></i> Clear</button>
<select asp-for="CurrentPage" onchange="ddlCurrentPageChange()" asp-items="Model.DdlPages" ></select>
<script>
function ddlCurrentPageChange() {
document.getElementById("form");
}
</script>
The issue is if I click the reset button and then change the DDL value, it posts to the handler ResetForm
You could always make your onchange the submit action, which will POST:
<form method="post" id="test">
<select asp-for=CurrentPage onchange="document.forms['test'].submit();" asp-items=#Model.ddlPages ></select>
</form>
page.cshtml.cs
public void OnPost(string currentPage)
{
MoveTo(currentPage);
}
public void MoveTo(string page)
{
Console.WriteLine(page);
}
EDIT: Fixed incorrect data as pointed out by #jeremycaney

ASP.NET CORE Razor Pages: How to avoid executing page handler 2nd time on page refresh?

When using method handlers to execute OnGet or OnPost methods, &handler=[action] query string gets added.
Problem is if user manually refreshes the page afterwards by hitting browser's refresh button, the same action will get executed for the 2nd time unintentionally.
What is the recommended approach to avoid this?
Problem is if user manually refreshes the page afterwards, same action
will get executed for the 2nd time.
For the browser refresh button click event, we can't prevent it. But, as a workaround, you could defined a TriggerCount property in the page model, and use a hidden field to store the value in the form, then in the handler method, get the hidden field value and based on the count to do something. Code as below:
code in the .cshtml.cs page:
public void OnPostDelete()
{
if (Request.Form["TriggerCount"].Count > 0)
{
TriggerCount = Convert.ToInt32(Request.Form["TriggerCount"]);
TriggerCount++;
}
if (TriggerCount < 2)
{
// do something.
Message = "Delete handler fired, Count:" + TriggerCount;
}
else
{
Message = "Over 2 times";
}
}
Code in the .cshtml page:
#page
#model RazorPageSample.Pages.HandlerPageModel
#{
}
<div class="row">
<div class="col-lg-1">
<form asp-page-handler="edit" method="post">
<button class="btn btn-default">Edit</button>
</form>
</div>
<div class="col-lg-1">
<form asp-page-handler="delete" method="post">
<input type="hidden" asp-for="TriggerCount" />
<button id="btndelete" disabled="#(Model.TriggerCount>=1?true:false)" class="btn btn-default">
Delete
</button>
</form>
</div>
</div>
<h3 class="clearfix">#Model.Message</h3>
the screenshot as below:

Navigate to new view on button click in ASP.NET Core 3.1 MVC

I am trying to navigate the user to a new page with a button click. I am having issues with rendering the new view. Any time I do click on the button, I either get an error for a dropdown on my page, or I get the home page view but with my desired route in the URL. I wanted to note that the user will be navigating to this page from the home page, which I made into my new landing page on the app. I wanted to point that out in case something I did here can be modified.
How I created a new landing page
I want to navigate from my landing page to my book inventory page.
My View (On the landing page):
<form method="post" asp-controller="Home" asp-action="Home" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="#(new SelectList(ViewBag.message, "ID", "bookName"))">
</select>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
<div class="row">
<div class="form-group">
<a asp-controller="BookInventory" asp-action="Index">
<input type="button" value="Book Inventory Page" />
</a>
</div>
</div>
My Controller (On my landing page)
public void GetBooksDDL()
{
List<BookModel> bookName = new List<BookModel>();
bookName = (from b in _context.BookModel select b).ToList();
bookName.Insert(0, new BookModel { ID = 0, bookName = "" });
ViewBag.message = bookName;
}
[HttpGet("[action]")]
[Route("/Home")]
public IActionResult Home()
{
GetBooksDDL()
return View();
}
My Controller (On my book inventory page):
[HttpGet("[action]")]
[Route("/Index")]
public IActionResult Index()
{
return View();
}
I wanted to note that my breakpoint on my book inventory controller does hit the 'return View()', but it will still render the items from the homepage.
The error I get with the book dropdown says:
ArgumentNullException: Value cannot be null. (Parameter 'items')
Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField).
I'm wondering why I'm getting this error when I'm trying to navigate to a different page. Since this is the new landing page, is it possible that it is passing along all of its data to the rest of the pages?
ArgumentNullException: Value cannot be null. (Parameter 'items')
Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.ctor(IEnumerable
items, string dataValueField, string dataTextField, IEnumerable
selectedValues, string dataGroupField).
About this error, it means that you didn't set the value for the select element, before return to the view, please check the ViewBag.message value, make sure it contains value.
Note: Please remember to check the post method, if the Http Get and Post method returns the same page, make sure you set the ViewBag.message value in both of the action methods.
I wanted to note that my breakpoint on my book inventory controller
does hit the 'return View()', but it will still render the items from
the homepage.
In the BookInventory Controller Index action method, right click and click the "Go to View" option, make sure you have added the Index view.
Based on your code, I have created a sample using the following code, it seems that everything works well.
Code in the Home Controller:
[HttpGet("[action]")]
[Route("/Home")]
public IActionResult Home()
{
GetBooksDDL();
return View();
}
[HttpPost("[action]")]
[Route("/Home")]
public IActionResult Home(BookModel book, string bookName)
{
GetBooksDDL();
//used to set the default selected value, based on the book id (bookName) to find the book.
List<BookModel> booklist = (List<BookModel>)ViewBag.message;
book = booklist.Find(c => c.ID == Convert.ToInt32(bookName));
return View(book);
}
Code in the Home view:
#model BookModel
#{
ViewData["Title"] = "Home";
}
<h1>Home</h1>
<form method="post" asp-controller="Home" asp-action="Home" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="#(new SelectList(ViewBag.message, "ID", "bookName", Model == null? 0:Model.ID))">
</select>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
<div class="row">
<div class="form-group">
<a asp-controller="BookInventory" asp-action="Index">
<input type="button" value="Book Inventory Page" />
</a>
</div>
</div>
Code in the BookInventory controller:
public class BookInventoryController : Controller
{
[HttpGet("[action]")]
[Route("/Index")]
// GET: BookInventory
public ActionResult Index()
{
return View();
}
The screenshot as below:
If still not working, please check your routing configuration, perhaps there have some issue in the routing configure.
Your anchor tag formation is incorrect. You cannot write a button within anchor tag.
Do something like this:
<a asp-action="Index" asp-controller="BookInventory" class="btn btn-primary">Book Inventory Page</a>
Here the class will help your anchor tag look like buttons. I hope you have used bootstrap in your project. If not, then use it.
Hope this helps.
Here is another simple way:
<button type="button" class="btn" onclick="window.location.href = '/YourPage'">Button Title</button>

knockout model - observable empty in IE 11

I have a set of input fields that are used to set search params, passed to the controller via knockout and ajax upon pressing the 'search' button.
Each input is bound to a property in a viewModel - each one is a ko.observable().
I have code bound to the keyup event for these fields that will invoke the same search operation when the return key is pressed.
In Chrome, this works fine, but in IE(11) this is never passed!
I have also noted that if I press the tab key to go to the next field, and THEN press return, the search parameter I expect is now populated.
Any ideas? at my wits end...
How do I do the same as pressing the tab key in code, without pressing the tab key?
I think IE's handling of the .change() event in jquery might be different to everyone else...
edited to include sample code - js:
var searchVm = function () {
var self = this;
self.reference = ko.observable("");
self.postCode = ko.observable("");
self.description = ko.observable("");
self.doSearch = function () {
var date = {
Ref: self.reference(),
PostCode: self.postCode(),
Desc: self.description()
};
// do the ajax call to controller
// ... etc ...
}
}
$('.searchField').keyup(function(e) {
if (e.which===13) {
$('#btnSearch').click();
}
});
the page:
<div class='indexRow'>
<label>Reference:</label>
<input type='text' class='searchField' data-bind="value: reference" />
</div>
<div class='indexRow'>
<label>PostCode:</label>
<input type='text' class='searchField' data-bind="value: postCode" />
</div>
<div class='indexRow'>
<label>Description:</label>
<input type='text' class='searchField' data-bind="value: description" />
</div>
<button data-bind='click: doSearch'>Search</button>

unobtrusive ajax form prevent cancel button from posting

Question: Why is cancel button posting to the controller like submit?
I have the form below loaded from a partial view. Submit works fine. The only thing I've been struggling with is why Cancel doesn't just dismiss the form. I've tried a variety of things like capturing the click event. I looked at http://jimmylarkin.net/post/2012/05/16/Broken-Validation-on-Cancel-Buttons-With-Unobtrusive-Validation-Ajax.aspx as a possible solution but I'm not sure this is the problem it's intended to address. No doubt it's some ignorance on my part. So what bonehead thing am I missing?
//click event loading the form.
<script>
$(document).ready(function () {
$('#editbtn').click(function () {
var url = "/Quiz/EditQuiz?id=#id";
$.get(url, function (data) {
$('#formdiv').html(data);
$("#formdiv").show();
});
});
</script>
//form inside partial view.
#using (Ajax.BeginForm("EditQuiz", "Quiz", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "formdiv"
}))
{
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
<div>
<fieldset>
.
.
<input type="submit" class = "btn btn-primary" value="Save" />
<button class = "cancel" >Cancel </button>
</fieldset>
</div>
}
I'm curious if your cancel button is whats causing the submit by default. Try replacing your <button class="cancel"> with an Html helper. How about #Html.ActionLink("Cancel", "Index"). This is a link that has text Cancel and redirects to action Index.