How to auto postback with Select2 using MVC Core - c#

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.

Related

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" />

Submitting form to two different actions in two different controllers asp.net mvc

I have googled a lot about this question but couldn't find any help regarding my scenario. So, here is the question
I have a form containing a single drop down, named Sections, user can select a Section and then user have two choices.
1-Add File to this Section By Going To File Uploading Form
2-Add Further Subsection By Going to Add Section FormThis is image of my form
#using (Html.BeginForm("SectionForm","Sections"))
{
<div class="form-group">
#Html.DisplayFor(s => s.SectionName)
#Html.DropDownListFor(s => s.SelectedSection, new SelectList(Model.Sections,"SectionId","SectionName"),"Select a Section",new {#class = "form-control",autofocus="autofocus"} )
</div>
<p>
If you don't see your desired section here, Click <strong>Add Section</strong>.
</p>
<button type="submit" class="btn btn-primary">Add Further Subsection</button>
<br />
Add File
}
<br>
SectionForm and FileForm are my actions and Sections and LawFiles are controllers.
anchor tag at the end won't work until I don't submit the form
You could use javascript to modify the action of your form. You’ll add a click event on the submit button and overwrite the default submit action.
<html>
<body>
<form id="myform">
<input type="submit" id="submit1"/>
<input type="submit" id="submit2"/>
</form>
</body>
<script>
$("#submit1").click(function() {
document.myform.action = “http://localhost/controller/action1”;
});
$("#submit2").click(function() {
document.myform.action = “http://localhost/controller/action2”;
});
</script>
</html>

Call a controller action from view

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>

Getting input from a ViewUserControl back to the controller on submit

I'll admit I'm new to MVC and this question might be a single case of RTFM. But I'm googling this problem and I can't seem to find a solution.
I've got a simple view used to fill out some details for a specific model. I need to render part of the form using Html.Partial (in truth this is a wrapper which renders old non-MVC controls used from another project).
I've no problems getting data FROM the controller INTO the view.
So what's the issue? How do I get user input from the partial view back to the controller after the user pressed the submit button?
Here's the view and controller I've currently got:
#model Poll
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Poll</h4>
<hr />
#*#Html.ValidationSummary(true)*#
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.Name)
#Html.Partial("~/ControlPlaceholder/QuestionPlaceholder.ascx", Model, new ViewDataDictionary(Model))
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Fill" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The view has been copied almost one-to-one from the standard generated edit view available in MVC5. Note that this is currently just a PoC - normally the whole thing should render a QuestionPlaceholder for every question in a Poll.
Here's the relevant part of the controller:
//
// GET: /Poll/Fill
[HttpGet]
public ActionResult Fill(Guid id)
{
var poll = pollRepository.Get(id);
return View(poll);
}
//
// POST: /Poll/Fill
[HttpPost]
public ActionResult Fill(Poll poll, FormCollection collection)
{
try
{
return RedirectToAction("Index");
}
catch
{
return View(poll);
}
}
it is so simple, just set name of inputs same as corresponding action parameters and let MVC ModelBinder do it's job. it's not important to render a partial in the form, it's input elements value would be passed to the action on submitting form.
another way is to use Request.Form["InputName"] that is not my first recommendation.

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