jQuery
<script>
$(document).ready(function () {
$('#nlSubscribeInitial').click(function () {
$('#nlSubscribeEmail').val($('#nlTextboxInitial').val());
$('#nlTextboxInitial').val('');
});
});
</script>
Form Currently in the Layout View
<div class="input-group">
<input class="form-control" type="text" id="nlTextboxInitial">
** Some other input / info here
<button id="nlSubscribeInitial" type="button" data-toggle="modal" data-target="#nlModal">Open Modal</button>
</div>
Modal currently in Layout View
<div class="modal-body">
<div class="form-group">
<label for="emailInputLogin">Email address</label>
<input type="email" class="form-control" id="nlSubscribeEmail" />
</div>
</div>
Currently this is my codes. After clicking the button on my page, it will open the modal popup.
The value of the textbox will be pass to the textbox located on the modal popup. Currently the form and the modal popup are on my Layout view.
I want to accomplish the same but this time I want call a View (.cshtml) and display it as a modal popup and passing my textbox value to another textbox that is in the View that is being called.
Thanks
Sumbit your email id value to your action, Fill your submited email id to model or viewbag or tempdata
Load That data to your redirected page
<div class="modal-body">
<form action="/somecontroller/someaction" method="post">
<div class="form-group">
<label for="emailInputLogin">Email address</label>
<input type="email" class="form-control" name="email" id="nlSubscribeEmail" />
</div>
</form>
</div>
Controller Action method,
public ActionResult SomeAction(string email){
// You can also construct model
ViewBag.Email = email;
// Return view
return View("SomeViewName");
}
Redirected page(i.e. SomeViewName.cshtml)
<h1>#ViewBag.Email</h1>
Related
I am facing the issue of data validation being executed on load of a new page even though it is clearly coming from a Get method. Is there something that's triggering the validations on page load?
I have a button on a view to add a new Student record in the new screen :
View :
<a type="button" id="btnAddStudent" href='#Url.Action("Details","Student")' class="btn btn-tertiary" title="Add Student">Add Student</a>
The controller code for the Details action method in Student Controller is as follows.
[HttpGet]
public ActionResult Details(StudentInfo model)
{
//This is populating the model parameters as expected.
helper.StudentInfo(ref model);
return View(model);
}
The view for the Details screen is as follows. The page loads but is throwing validation errors even though it's a Get method.
<form id="frmSubmit" asp-action="Details" asp-controller="Student" method="post">
<input type="hidden" asp-for="StudentId" />
<div class="row">
<div class="col-xs-12">
#Html.ValidationSummary("", new { #class = "alert alert-danger validation" })
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label asp-for="Name">*StudentName</label><br />
<input asp-for="Name" class="form-control" maxlength="100" placeholder="Enter student name..." />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label asp-for="AddressLine1"></label><br />
<input asp-for="AddressLine1" class="form-control" placeholder="Enter address..." />
<span asp-validation-for="AddressLine1" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label asp-for="AddressLine2"></label><br />
<input asp-for="AddressLine2" class="form-control" maxlength="100" />
<span asp-validation-for="AddressLine2" class="text-danger"></span>
</div>
</div>
</div>
<div class="box">
<div class="form-group pull-right">
<button type="submit" class="btn btn-primary" value="save"> Save</button>
</div>
</div>
Is there something I am doing wrong? I have verified that the debug control goes to the Get method.There's alos no on load scripts which are doing any sort of validation.
1.Your get method contains the model parameter, when the request hit the method it will judge the ModelState by default. And when you hit the get method by your shared <a>, it send request without any data, so the ModelState is invalid.
2.Default Tag helper displays ModelState's value not Model.
In conclusion, you will render the ModelState error although it is a get method.
Two ways you can resolve this problem. The first way is that you can add ModelState.Clear() before you return View:
public ActionResult Details(StudentInfo model)
{
ModelState.Clear(); //add this....
helper.StudentInfo(ref model);
return View(model);
}
The second way is do not add the model as parameter:
public ActionResult Details()
{
var model = new StudentInfo();
helper.StudentInfo(ref model);
return View(model);
}
I know it must be something stupid, but I cant seem to figure this out. I have the following in a view:
#using (#Html.BeginForm("ReceiveForm1", "Home", FormMethod.Post))
{
<div class="form-group">
<label for="organizationID">Organization ID</label>
<input type="number" class="form-control" asp-for="organizationID" aria-describedby="emailHelp" placeholder="Enter Organization ID">
</div>
<div class="form-group">
<label for="externalPersonalID">External Personal ID</label>
<input type="number" class="form-control" asp-for="externalPersonalID" placeholder="Enter External Personal ID">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="number" class="form-control" id="phoneNumber" asp-for="phoneNumber" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
}
And I have the following code in my controller:
[HttpPost]
public ActionResult ReceiveForm1(FormCollection collection)
{
IEnumerable<Form1Return> personData = GetPersonInformation(collection);
return View(personData);
}
When I run the code, and enter data into the form, and click the submit button, I run to a breakpoint set on call to GetPersonInformation. When I do a watch on collection, there are no elements. So for some reason, the form data is not making it to the controller. Any idea why?
Thanks.
The 'Microsoft.AspNetCore.Mvc.ModelBinding.Binders.FormCollectionModelBinder' cannot bind to a model of type 'Microsoft.AspNetCore.Http.FormCollection'. Change the model type to 'Microsoft.AspNetCore.Http.IFormCollection' instead.
Please try this:
[HttpPost]
public ActionResult ReceiveForm1(IFormCollection collection)
{
IEnumerable<Form1Return> personData = GetPersonInformation(collection);
return View(personData);
}
I've seen this happen when input's don't have their name attribute set. The relevant section on W3Schools has this nugget which confirms this is likely the case.
Note: Only form elements with a name attribute will have their values passed when submitting a form.
I'm building a web application using ASP.NET CORE 3.1. There is a data table(EvCode) that has two columns, EventCode (key field) and EventType. On the page that lets a user add a new event there are a number of fields. Among them is EventCode and EventType. When the EventCode is entered and the user exits the field, I want to trigger an event that queries the EvCode table using the the value in the EventCode field to select the EventType, then populate the the EventType field with the value.
If I add a button to the page, I can run the event handler. I need the event handler to run automatically when the value in the EventCode field is changed.
Any suggestions or ideas on how to do this are appreciated.
Fei Han - Thank you for your suggestions and code. I used a different project where I trying to accomplish the same thing. The only differences, rather than using EventCode I used FamilyCode, and rather than use EventType I used FamilyName. The handler (OnGetFamilyNameByCode) was never called.
I've included my code, maybe you can see what I've done wrong.`
<form method="get" >
<div class="border backgroundWhite">
<div class="form-group row">
<div class="col-2">
<label asp-for="PublisherFamilyVM.PubDataList.LastName"></label>
</div>
<div class="col-6">
<input asp-for="PublisherFamilyVM.PubDataList.LastName" class="form-control" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.LastName" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="PublisherFamilyVM.PubDataList.FirstName"></label>
</div>
<div class="col-6">
<input asp-for="PublisherFamilyVM.PubDataList.FirstName" class="form-control" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.FirstName" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
#Html.LabelFor(m => m.PublisherFamilyVM, "Family Code/Name:")
</div>
<div class="col-2">
<!-- <input asp-for="PublisherFamilyVM.PubDataList.FamilyCode" class="form-control" /> -->
<input id="input_family_code" class="form-control" type="text" value="" onblur="getfamilyname();" />
</div>
<div class="col-4">
<!-- <input asp-for="PublisherFamilyVM.FamilyList.FamilyName" class="form-control" /> -->
<input id="input_family_name" class="form-control" type="text" value="" />
</div>
<span asp-validation-for="PublisherFamilyVM.PubDataList.FamilyCode" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-6 offset-2">
<partial name="_CreateAndBackToListButton" />
</div>
</div>
</div>
</form>
#section Scripts{
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
function getfamilyname() {
var familycode = $("#input_family_code").val();
if (familycode != "") {
$.getJSON(`/eventinfo?handler=FamilyNameByCode&familycode=${familycode}`, function (data) {
//console.log(data);
$("#input_family_name").empty();
$("#input_family_name").val(data);
});
}
</script>
}
***** PageModel *****
public JsonResult OnGetFamilyNameByCode(string familycode)
{
//code logic here
//retrieve data from database based on famiycode
return new JsonResult(familycode);
}
When the EventCode is entered and the user exits the field, I want to trigger an event that queries the EvCode table using the the value in the EventCode field to select the EventType, then populate the the EventType field with the value.
To achieve above requirement, you can try to make AJAX request to handler method then dynamically populate value of EventType input field based on returned value in blur event of EventCode input field, like below.
<input id="input_event_code" type="text" value="" onblur="geteventtype();" />
<input id="input_event_type" type="text" value=""/>
JS code
function geteventtype() {
var eventcode = $("#input_event_code").val();
if (eventcode!="") {
$.getJSON(`/eventinfo?handler=EventTypeByCode&eventcode=${eventcode}`, function (data) {
//console.log(data);
$("#input_event_type").empty();
$("#input_event_type").val(data);
});
}
//...
}
handler method
public JsonResult OnGetEventTypeByCode(int eventcode)
{
//code logic here
//retrieve data from database based on eventcode
//...
return new JsonResult(eventtype);
}
Test Result
Update:
A 404 error does on the $.getJSON line of code indicating the url cannot be found. I replaced '/eventinfo?handler= FamilyNameByCode&familycode=${familycode}' - with - '/Create?handler = FamilyNameByCode&familycode=${familycode}' Do a need to add the folder or something else?
Please check if your Create model class look like below.
public class CreateModel : PageModel
{
//properties here
//...
public void OnGet()
{
}
public JsonResult OnGetFamilyNameByCode(int familycode)
{
//code logic here
//retrieve data from database based on eventcode
//...
return new JsonResult("FamilyName_Here");
}
}
I am currently working on a basic To Do List on ASP.NET CORE. I have a button on top of the To-Do list to says "Add Task" upon clicking on the button you'll be re-directed to a Create Task Form. At the moment when click on the Add Task button to be re-directed to the form I am getting a localhost not found error. The URL is correct as it says http://localhost:51797/Todo/Create but my .cshtml page does not appear. I'm new to ASP.Net so apologies if the reason is obvious but I have gone through my code and I cant seem to find why this is happening.
[HttpPost]
[ActionName("Create")]
public ActionResult Create(int? id, string newText)
{
int i = id ?? 0;
TodoListItem toDo = _todoListService.GetList(i);
toDo.Text = newText; //Set new text
_todoListService.WriteToFile(toDo);
return RedirectToAction("Index");
}
}
This is my Create.cshtml page
#model TodoListItem
#{
ViewData["Title"] = "Create";
}
<h2>Add Task</h2>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Text" class="control-label"></label>
<input asp-for="Text" class="form-control" name="newText" />
<span asp-validation-for="Text" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
app.UseMvc(routes =>
routes.MapRoute(
name: "create",
template: "{controller=Todo}/{action=Create}");
});
You need an HTTPGET attribute for the GET action, which should return the create view with an empty model.
public IActionResult Create()
{
return View(new TodoListItem());
}
So when you click on Add Task, it will execute this action method and returns the create view.
I append my select option from database table. Select option has two type
scalar
event
If the option type is scalar, I need to show 2 input fields (alarm, reset) so that user can inset values in it and when the option type is event I need to hide 2 input fields (alarm, reset) so that user cannot inset values in it.
When the option type is scalar, my form saves successfully but when option type is event form submit button not going to perform any action.
Can you please help?
Here is my code
HTML
<div class="row">
<form method="post" action="/Home/SaveTriggers" class="form-inline">
<div class="col-md-12">
<div class="col-md-2">
<select name="sourceId" class="select2" required>
#foreach (var i in ViewBag.opt)
{
<option value="#i.Id,#i.name,#i.type" id="opt">#i.name</option>
}
</select>
</div>
<div class="col-md-2">
<input id="alarm" name="alarm" type="text" placeholder="alarm" style="display:none" required />
</div>
<div class="col-md-2">
<input id="reset" name="reset" type="text" placeholder="reset" style="display:none" required />
</div>
<div class="col-md-1">
<input type="text" name="delay" id="delay" placeholder="delay" required />
</div>
<div class="col-md-3">
<select class="address2" name="action" id="select" required>
<option selected disabled>Select alarm action</option>
<option>John Doe, Switch on warning light</option>
<option>John Doe</option>
<option>Do anything</option>
</select>
</div>
<div class="col-md-2">
<button id="delete2" type="button" class="btn btn-default">Delete</button>
</div>
<button class=" add btn btn-primary" type="submit">Add</button>
</div>
</form>
</div>
Jquery(as i have to hide or show alarm or reset fields respectively)
<script>
$(document).ready(function () {
$(".select2").change(function () {
var text = $(".select2 option:selected").text();
var val = $(".select2 option:selected").val();
var res = val.split(",");
var type = res[2];
if (type == "scalar") {
document.getElementById("reset").style.display = "block";
document.getElementById("alarm").style.display="block"
}
else if(type=="event") {
document.getElementById("reset").style.display = "none";
document.getElementById("alarm").style.display = "none"
var alarm = document.getElementById("alarm");
}
});
});
</script>
The problem is most likely your inputs for alarm and reset.
If type is event, they are hidden and will most likely hold no value. But since they are required, the form will not submit until that error is resolved.
So you can either remove the required attribute from those 2 input fields, populate them with default values or use novalidate in your form tag. This disables form validation. You'd have to validate your inputs by hand in javascript.
<div class="col-md-2">
<input id="alarm" name="alarm" type="text" placeholder="alarm" style="display:none" />
</div>
<div class="col-md-2">
<input id="reset" name="reset" type="text" placeholder="reset" style="display:none" />
</div>
<div class="col-md-2">
<input id="alarm" name="alarm" type="text" placeholder="alarm" style="display:none" required />
</div>
<div class="col-md-2">
<input id="reset" name="reset" type="text" placeholder="reset" style="display:none" required />
as you're having required attribute in your input element, the validation is getting triggered and not letting you submit the form.
i would suggest you to do a validation on jquery on submit instead of using default html5 validation