Call a controller action from view - c#

I am trying to call an action from the controller using onclick method. For some reason it's not returning action I want, it's always jumping to public ActionResult Index() by default.
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Register" class="btn btn-default" onclick="location.href='#Url.Action("RegisterIndex", "Register")'"/>
</div>
</div>
NOTE
I have created view automatically with a model. It's validating input for me by using already generated javascripts. If I change input tag to button it's not gonna do the required validation.

window.location.href does a GET request, that's why it didn't pass your input values to the server.
When you have <input type="submit"> inside a form, clicking it will submit the form with all data you need. I think this is what you want, but you just want it to submit to another action.
To achieve this, I suggest this solution:
Create a hidden field in the form. Its data will be sent to the server.
In your server, base on that hidden value, you can redirect to the appropriate action
Please feel free to ask me if you find anything unclear :)

The <input type="submit">, when inside a form element, will submit the form when clicked unless you return false or event.preventDefault();
returning false will prevent the default behavior for your submit.
EDIT
window.location.href will cause a GET request so your data will not be posted using this method.
HTML
#using (Html.BeginForm())
{
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnSubmit" value="Register" class="btn btn-default"/>
</div>
</div>
}
Javascript
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () { window.location.href = '#Url.Action("RegisterIndex", "Register")'; return false; });
});
</script>

Related

Clicking 2 submit buttons in the same page

I have a project in .Net Core with Razor Pages and I have the form bellow that contains some input fields and 2 submit buttons.
<form class="form-style" method="post" id="createForm">
<div class="form-group button-position col-md4">
<input type="submit" id="placeRequest" name="placeRequest" value="Place Request" class="btn btn-primary" />
</div>
<div class="form-group button-position col-md4">
<input type="submit" value="GetHour" asp-page-handler="Hour" class="btn btn-primary btn-style" formnovalidate />
</div>
</form>
I need to be able to click the first submit button (GetHour) and then click the second one (Placer Request)
In my Razor Page model I have
public async Task<IActionResult> OnPost()
{
//code that will be executed when the Place Request button is clicked
}
public async Task OnPostGetHour()
{
////code that will be executed when the Get Hour button is clicked
}
The problem is that I am not allowed to make the 2 submits. If I only do one of them, it works but the second one does nothing
Is there any way I could make both of the submits?
This is because once you click the first submit button, The page does a redirect and loads again.
This is the nature of form submission. If you want to click both the buttons. Change the button type from "submit" to "button".
Then create 2 click handlers and handle the form submitting using Ajax
<form class="form-style" method="post" id="createForm">
<div class="form-group button-position col-md4">
<input onclick="onBtn1Click()" type="button" id="placeRequest" name="placeRequest" value="Place Request" class="btn btn-primary" />
</div>
<div class="form-group button-position col-md4">
<input onclick="onBtn2Click()" type="button" value="GetHour" asp-page-handler="Hour" class="btn btn-primary btn-style" formnovalidate />
</div>
</form>
Then write 2 JavaScript functions
function onBtn1Click()
{
//Submit code via Ajax here
}
function onBtn2Click()
{
//Submit code via Ajax here
}

Focus back on textbox after submitting using ASP.NET Core MVC

I am trying to introduce a dynamic search function in my project. I have created a search form in my view which submits on keyup but the issue that I'm not facing is that when the view reloads, the text box is no longer in focus and so the user needs to click back onto it which obviously isn't ideal.
My view is set up as follows:
<form id="searchForm" asp-action="Index" method="get">
<div class="row">
<div class="col-9">
<input type="text" id="fooSearch" name="searchString" value="#ViewData["currentFilter"]" class="form-control" />
</div>
<div class="col-3">
<div class="row">
<div class="col-6">
<input type="submit" value="Search" class="btn btn-outline-secondary form-control" />
</div>
<div class="col-6">
<a asp-action="Index" asp-route-recent="true" class="btn btn-outline-secondary form-control">Recent</a>
</div>
</div>
</div>
</div>
</form>
with the following JQuery script to submit on keyup
$(function () {
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
});
});
</script>
Can anyone help me to retain focus on the search textbox when the DOM is loaded?
To give the focus back to the searchbar, you can use jQuery's focus(), e.g.:
$("#fooSearch").focus();
Now, where you place this depends on whether your form submit is synchronous (and makes the page reload) or asynchronous.
If the submit is asynchronous, then you can place this in your keyup event handler, right after the code that submits:
$('#fooSearch').keyup(function () {
$('#searchForm').submit();
$("#fooSearch").focus(); //focus back on the search bar
});
Otherwise, you will need to call focus() from an onload event:
$(document).ready(function() {
$("#fooSearch").focus();
});
In all cases, first load or reload (submit), the focus should be on the search textbox so I think that you can just focus the textbox on load.
$(function() { $("#fooSearch").focus();});
The problem you may encouter is that the cursor will not be in the end of the keywords. So I think that the best option here is to use Ajax to the update the results each time the user change the keywords. Maybe waiting a few seconds before each update is a good idea also.
If you are using html5 you can just add autofocus to your html tag something like:
<input type="text" id="fooSearch" autofocus ="autofocus" name="searchString" value="#ViewData["currentFilter"]" class="form-control" />

html button is activating asp validation in html input form - Why?

I'd want to ask why after clicking on my custom button that just appends text to div that's inside form, then it activates asp validation of that form?
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div id="append_area">
</div>
<button id="appendChild" onclick="addText()">add new thing</button>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
<script>
function addText()
{
var div = document.getElementById('append_area');
div.innerHTML += `test`;
}
</script>
Set your button type as button
<button type="button" id="appendChild" onclick="addText()">add new thing</button>
As described in W3C documentation, default type of the <button> element can vary across different browsers, so it is a good practice to always specify it explicitly.
In this case, the default value is submit, so by clicking the button you are inadvertently causing the submit action and hence also validation to be performed as well.
To fix this, just specify the button type explicitly as button:
<button type="button" />
You can also do this:
<script>
function addText()
{
var div = document.getElementById('append_area');
div.innerHTML += `test`;
return false;
}
</script>
then you can call in code onclick="return addText()"
When you submit a form to a CGI program that resides on the server, it is usually programmed to do its own check for errors. If it finds any it sends the page back to the reader who then has to re-enter some data, before submitting again. A JavaScript check is useful because it stops the form from being submitted if there is a problem, saving lots of time for your readers.
<button type="button" id="ChildForm" onclick="add()">add new </button>
The CGI script is still more reliable, as it always works regardless of whether JavaScript is enabled on the client-side or not; but having this extra safety barrier is a nice thing to have in place. It makes your page much more user-friendly and takes out the frustration of having to fill out the same form repeatedly. It's also very precise, as you can point out the exact field where there's a problem.

How to auto postback with Select2 using MVC Core

I am trying to use Select2.js within my MVC 6 (Core) project, where if a user selects a value (or multiple values) within the first listbox, then they are then provided with an updated list of values within the second listbox. So for example... if a user selects "Ford" and "Renault" from the Manufacturer listbox, then they are only provided with relevant values in the Brand listbox e.g. Mondeo, Mustang, Clio, Megane etc.
My View syntax is:
#model MyProject.ViewModels.MyViewModel
<script type="text/javascript">
$(document).ready(function () {
$('#ManufacturerID').select2({
placeholder: 'Please make a selection...',
width: 500
});
$('#BrandID').select2({
placeholder: 'Please make a selection...',
width: 500
});
});
</script>
<form asp-action="Generation">
<div class="form-horizontal">
<div class="col-md-10">
#Html.ListBoxFor(model => model.ManufacturerID, Model.ManufacturerNames)
#Html.ListBoxFor(model => model.BrandID, Model.BrandNames)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-default" />
</div>
</div>
</form>
If I click the submit button, the post action method successfully acquires a list of Manufacturer ID's:
// POST: MyController/Generation
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Generation(MyViewModel myViewModel, IEnumerable<int> manufacturerID)
{
return RedirectToAction("Generation");
}
But what I really want is something similar to AJAX Update Panel in Web Forms where the call to the controllers post action method is performed immediately on selecting an option from the listbox, not when the user clicks submit.
Your help is greatly appreciated.
Regards,
X22
$(document).ready(function(){
pageInit();
});
function pageInit(){
$('#ManufacturerNames').off();
$('#ManufacturerNames').on('change', function(e){
//ajax request here
//call pageInit() in your callback to reattach select2
//and event handler if you are fully replacing the dropdown.
});
$('#BrandNames').off();
$('#BrandNames').on('change', function(e){
//ajax request here
//same as callback above depending on how you go about doing this.
});
}
This is the manual way but since you are using a library like select2, they may provide an easy way to set this up in your initialization.

razor/mvc code running on page load instead of onclick?

I have a loop that creates some buttons and (is meant to) make a function call when that button is pressed.
foreach (Answer a in qanswers)
{
//Guid answerid = new Guid();
<form method="post" action="">
<div class="float-left">
<input type="submit" value="#a.Answer1" class="submit" style="width:600px" onmousedown="#{saveTest(a, module, user, quest, healthsafety);}">
<br /><br />
</div>
</form>
}
However, it calls the "saveTest" procedure at page load for each button produced, rather than onmousedown/onmouseclick.
Is it possible to change this?
I assume from this that saveTest is a server side function that you are trying to call.
onmousedown is a client side event and can only directly run client side script.
If you wish to call a server side function then you will need to specify an action in the form that the page will post pack to.
Have a look here for more on this
http://msdn.microsoft.com/en-us/library/system.web.mvc.html.formextensions.beginform(v=vs.108).aspx
A quickly modified version of your code would be:
foreach (Answer a in qanswers)
{
using (Html.BeginForm("saveTest", "ControllerName"))
{
<div class="float-left">
<input type="submit" value="#a.Answer1" class="submit" style="width:600px")>
<br /><br />
</div>
}
}
The button will submit to the controller and action that has specified in the form. So please check carefully which controller and action you have specified.
using (Html.BeginForm("saveTest", "Controller"))
{
}
This is the way you have to specify your form.
Regards,
Pavan.G

Categories

Resources