I am learning ASP MVC and I try do form, and when you click the button on the form, I want to add some content to div in this form.
#using (Html.BeginForm())
{
<div>
<input type="button" value="Click to edit address" onclick="#String.Format("addAddress()")" />
<div id='divResult'>
Here I want to add new conntent after click button.
</div>
<div>
}
My Java Script function does't work:
<script type="text/javascript">
function addAddress() {
$('#divResult').replaceWith("#Html.EditorFor(m => m.User.HomeAddress)");
}
</script>
Can anyone help me? I want to fill my User (model.User) object and post filled to server, but Athe address you can fill only after click button, because it has a lot of field to be filled, but address is not necessary.
Try this:
#using (Html.BeginForm())
{
<div>
<input type="button" value="Click to edit address" onclick="addAddress()" />
<div id='divResult' hidden='hidden' >
#Html.EditorFor(m => m.User.HomeAddress)
</div>
</div>
}
-
<script type="text/javascript">
function addAddress() {
$('#divResult').show();
}
</script>
Related
I'm designing a time clock web app, where on the main page where the user can clock in/out if they have a current activity record or not (from a SQL server database)
I have the following form:
<form asp-action="RegisterClockAction" asp-antiforgery="false" method="post">
<div class="form-group">
<input asp-for="ActiveFlag" type="hidden"/>
</div>
<div class="form-group row">
<div class="col-sm-5 offset-sm-1 center-column">
<button id="clock-in-btn" type="submit" class="btn clock-button" disabled>Clock In</button>
</div>
<div class="col-sm-5 center-column">
<button id="clock-out-btn" type="submit" class="btn clock-button" disabled>Clock Out</button>
</div>
</div>
</form>
Then I have the following JavaScript for this specific View
<script type="text/javascript">
$(function() {
const activeFlag = #Html.Raw(Json.Serialize(Model.ActiveFlag));
if (activeFlag) {
$("#clock-out-btn").prop("disabled", false);
} else {
$("#clock-in-btn").prop("disabled", false);
}
});
$("form").submit(function() {
if ($(this).valid()) {
$(this).find(":submit").attr("disabled", "disabled");
}
});
</script>
Now the form submit event does prevent from double submission, but is this the correct way I should be doing it?
Not sure if it's necessary to know, but all the controller POST action does, if the active flag is true then we find the record in the database, update it and commit the changes to mark inactive. Otherwise, we create a new record to append into the database. Then, I just redirect back to the Index view to rebuild the model.
you can fix this by using javascript
you should use event.preventDefault() so that the default action of the event will not be triggered again.
$("form").submit(function(e) { // 'e' <- add this line of code
e.preventDefault(); // <- add this line of code
if ($(this).valid()) {
$(this).find(":submit").attr("disabled", "disabled");
}
});
I am trying to add Html code inside a #functions {} codeblock where if it matches some condition it will alert the user.
this is what I have so far, and I am getting the error CS0103: The name 'alert' does not exist in the current context
this is the code piece that is throwing the error.
#functions{
void doSomething(){
if(ViewBag.token != null){
#alert("#ViewBag.token");
}
}
}
Is there a way to embed alert() inside a C# code-block within .cshtml
this is the entire code which this function is in
#using System.Web.Mvc
#using System.Web.Mvc.Html
#using System
#using System.Web.UI
#model Dependency_Injection_MEF_MVC.Models.Payment
#section Scripts{
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
</script>
<script type="text/javascript">
$(function () {
var $form = $('#payment-form');
$form.submit(function (event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
ViewBag.token = token;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="Token">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
}
<div class="row">
<div class="col-md-12 form-column">
<div class="form-container">
<form asp-controller="home" asp-action="processpayment" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-group">
<h3>Membership Amount: USD XX</h3>
</div>
<div class="form-group">
<label for="cardNumber">Card Number</label>
<input class="form-control form-input" id="cardNumber" type="text" size="20" data-stripe="number" style= "width:250px;height:25px;font-size:120%">
</div>
<div class="form-group">
<label>Expiration (MM/YY)</label>
<div>
<input class="form-control form-input date-input" type="text" size="2" data-stripe="exp_month" style= "width:250px;height:25px;font-size:120%">
<input class="form-control form-input date-input" type="text" size="2" data-stripe="exp_year" style= "width:250px;height:25px;font-size:120%">
</div>
</div>
<div class="form-group">
<label for="cvc">CVC</label>
<input class="form-control form-input" id="cvc" type="text" size="4" data-stripe="cvc" style= "width:250px;height:25px;font-size:120%">
</div>
<input class="btn btn-default" onclick="doSomething()" id="submit" value="Submit Payment">
</form>
</div>
</div>
</div>
#functions{
void doSomething(){
if(ViewBag.token != null){
alert("#ViewBag.token");
}
}
}
Functions are intended to be completely server-side. But that script can be easily embeddable; if you move that to the page where you want it called, just do:
#if(ViewBag.token != null){
<script>
alert("#ViewBag.token");
</script>
}
And this will get rendered if the token exists. Functions aren't needed for this; this could be inside of a #helper though.
I visited through different links but couldn't find desired answer. I am not using model for this view. Before sending data to server I want to check whether the text input is null or not.How can I validate it?
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<h2>Student Information</h2>
#using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
{
<label>First Name:</label>
<input type="text" class="form-control" name="firstname" id="f_name" />
<button type="submit" class="btn btn-success" >Insert</button>
}
</div>
<script>
$(function () {
$("#target".submit(function (event) {
event.preventDefault();
//return false;
})
})
</script>
Try this, I use empty string ('') instead of null since usually empty textbox are just empty string and not necessarily null.
<script>
$(function () {
$('button.btn').unbind();
$('button.btn').click(function () {
if($("#f_name").val() == ''){
return false;
}
return true;
})
})
</script>
If you dont want custom script for validating data on client side, you can use jquery.validate.js and jquery.validate.unobstrusive.js. This will work just like mvc validation rules(Actually this validation logic is generated by MVC itself on the view when client side validation is enabled).
Just add this three script file inside your page.
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>
Or you can select from your Script folder inside MVC application.
And Try to add following attribute in your Htmlelement for validation.
<div class="container">
<h2>Student Information</h2>
#using (Html.BeginForm("insert", "Menu", FormMethod.Post, new { id="target"}))
{
<label>First Name:</label>
<input data-val="true" data-val-required="First Name field is required." type="text" class="form-control" name="firstname" id="firstname" />
<span class="field-validation-valid" data-valmsg-for="firstname" data-valmsg-replace="true"></span>
<button type="submit" class="btn btn-success" >Insert</button>
}
</div>
This will work just like MVC validation inside your view.
You can get more information how to use JqueryValidate and jquery unobtrusive by clicking on this link : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
You can get the value with a simple jQuery statement - $("#f_name").val() and then check if it is null $("#f_name").val() == null
So your complete javascript would be
<script>
$(function () {
$("#target".submit(function (event) {
event.preventDefault();
if($("#f_name").val() == null){
return false;
}
return true;
})
})
</script>
I have a question concerning updating a partial view from another partial view where the first view is contained.
I have 4 dropdowns that are populated based on the previous selections, then the user may submit their selections and a database is queried and a table is populated based on their selections. I should note that I am very new to asp.net mvc and it's all still quite confusing to me.
Below is my code:
<form action="/Home/LoadRelease" method="post" style="text-align: center;">
#*Headers*#
<div id="BusinessAreaLabel" class="inline" style="width:14em;">Business Area</div>
<div id="GenericProjectLabel" class="inline" style="width:13em;">Generic Project</div>
<div id="ProjectLabel" class="inline" style="width:17em;">Project</div>
<div id="ReleaseLabel" class="inline" style="width:13em;">Release</div>
<br />
#*Dropdowns*#
<select id="BusinessAreaDropDown" name="BusinessArea" onchange="javascript: FillGenericProject(); FillProject(); FillReleases();" style="width: 13em;">
#Html.Partial(#"Dropdowns\_BusinessArea", Model.ProjectViewModels);
</select>
<select id="GenericProjectDropDown" name="GenericProject" onchange="javascript: FillProject(); FillReleases();" style="width: 13em;"></select>
<select id="ProjectDropDown" name="Project" style="width: 17em;" onchange="javascript: FillReleases();"></select>
<select id="ReleaseDropDown" name="Release" style="width: 13em;"></select>
<input type="submit" id="GoButton" style="visibility:hidden;" value="Go" />
</form>
<form id="ReleaseTableBody" style="text-align:center;">
#Html.Partial("_TableBody", Model.OpenCloseViewModels) //I want to update this.
</form>
<br />
and Home/LoadRelease:
[HttpPost]
public ActionResult LoadRelease(string Project, string Release)
{
var ProjectID = _ProblemReportsDB.ProjectMaps
.Where(r => r.Project == Project)
.Select(r => r.ID).FirstOrDefault();
ViewBag.Project = Project;
var Releases = from row in _ProblemReportsDB.PlannedOpenCloses
where (row.Project == ProjectID)
select row;
return PartialView("_TableBody", Releases.ToList());
}
The above loads the partial view "_TableBody", but actually directs to the page containing only the contents of _TableBody.
Ideally, I would remain on the page displaying and only update the _TableBody section of the page. I think I understand why it is currently failing, I'm telling it to run the action /Home/LoadRelease, which returns the _TableBody partial view, which it loads.
I'm having trouble figuring out how to make it only update the _TableBody partial view.
Thanks for any help you can offer.
EDIT:
Attempting Jasens method I have begun using an ajax function: Still loads to another page instead of updating the partial:
Code:
#using (Html.BeginForm("LoadRelease", "Home", FormMethod.Post, new { id = "DropDownForm", style="" }))
{
#*Headers*#
<div id="BusinessAreaLabel" class="inline" style="width:14em;">Business Area</div>
<div id="GenericProjectLabel" class="inline" style="width:13em;">Generic Project</div>
<div id="ProjectLabel" class="inline" style="width:17em;">Project</div>
<div id="ReleaseLabel" class="inline" style="width:13em;">Release</div>
<br />
#*Dropdowns*#
<select id="BusinessAreaDropDown" name="BusinessArea" onchange="javascript: FillGenericProject(); FillProject(); FillReleases();" style="width: 13em;">
#Html.Partial(#"Dropdowns\_BusinessArea", Model.ProjectViewModels);
</select>
<select id="GenericProjectDropDown" name="GenericProject" onchange="javascript: FillProject(); FillReleases();" style="width: 13em;"></select>
<select id="ProjectDropDown" name="Project" style="width: 17em;" onchange="javascript: FillReleases();"></select>
<select id="ReleaseDropDown" name="Release" style="width: 13em;"></select>
<button type="submit" id="GoButton" style="visibility:hidden;">Go</button>
}
#*</form>*#
<form id="ReleaseTableBody" style="text-align:center;">
#Html.Partial("_TableBody", Model.OpenCloseViewModels)
</form>
<br />
In index: (Parent of _DropDownBody):
<script src="~/Scripts/jquery-1.10.2.js">
$(document).ready(function () {
$("#DropDownForm").on("submit", function (event) {
event.preventDefault();
var form = $(this);
var Project = $('#ProjectDropDown').val();
var Release = $('#ReleaseDropDown').val();
alert(Project);
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: form.serialize()
})
.done(function (result) {
$("#ReleaseTableBody").html(result);
});
});
});
</script>
Using A. Burak Erbora's method produces the same issue as well. Am I missing something?
Final edit: Jasen's answer worked and allowed me to update a partial view without redirecting. Still having issues getting the partial to show my content, but as far as the question goes - Jasen's answer works!
Submitting a form will cause navigation. Since you want to stay on the same page you'll need to trap the submission event and use AJAX to update your page.
Main View
#using(Html.BeginForm("LoadRelease", "Home", FormMethod.Post, new { id = "DropDownForm", style = "" })
{
<!-- your drop down inputs -->
<button type="submit">Go</button>
}
<form id="ReleaseTableBody" style="text-align:center;">
#Html.Partial("_TableBody", Model.OpenCloseViewModels) //I want to update this.
</form>
Then the page script (don't forget to load jquery.js before this). Also note if you are embedding partial views you need to move this script "up" to the parent since #section will not render in partials.
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#DropDownForm").on("submit", function(e) {
// prevent default submission
e.preventDefault();
// do AJAX post instead
var form = $(this);
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: form.serialize()
})
.done(function(result) {
// replace content
$("#ReleaseTableBody").html(result);
});
});
}
</script>
Controller action unchanged
[HttpPost]
public ActionResult LoadRelease(string Project, string Release)
{
// search
return PartialView("_TableBody", results);
}
First off, I'd recommend you use html helpers. What you seem to need here is an ajax call instead of a standard form post. Instead of
<form action="/Home/LoadRelease" method="post" style="text-align: center;">
you can use
#using (Ajax.BeginForm("LoadRelease", "Home", options)){
#*Headers*#
<div id="BusinessAreaLabel" class="inline" style="width:14em;">Business Area</div>
<div id="GenericProjectLabel" class="inline" style="width:13em;">Generic Project</div>
<div id="ProjectLabel" class="inline" style="width:17em;">Project</div>
<div id="ReleaseLabel" class="inline" style="width:13em;">Release</div>
<br />
#*Dropdowns*#
<select id="BusinessAreaDropDown" name="BusinessArea" onchange="javascript: FillGenericProject(); FillProject(); FillReleases();" style="width: 13em;">
#Html.Partial(#"Dropdowns\_BusinessArea", Model.ProjectViewModels);
</select>
<select id="GenericProjectDropDown" name="GenericProject" onchange="javascript: FillProject(); FillReleases();" style="width: 13em;"></select>
<select id="ProjectDropDown" name="Project" style="width: 17em;" onchange="javascript: FillReleases();"></select>
<select id="ReleaseDropDown" name="Release" style="width: 13em;"></select>
<input type="submit" id="GoButton" style="visibility:hidden;" value="Go" />
}
and somewhere in your html you have:
<div id="ReleaseTableBody">
#Html.Partial(_TableBody", Model.OpenCloseViewModels)
</div>
you will need to define the options object for the Ajax helper like:
var options = new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "ReleaseTableBody",
OnBegin = "OnCallbackBegin",
OnFailure = "OnCallbackFailure",
OnSuccess = "OnCallbackSuccess",
LoadingElementId = "loading"
};
you can also use the event callback methods if you define their JavaScript functions like:
<script>
function OnCallbackBegin() {
$(".btn-loading-icon").show();
$(".btn-loading-text").hide();
}
function OnCallbackSuccess(data) {
//alert("onSuccess: result = " + data.result);
$(".btn-loading-icon").hide();
$(".btn-loading-text").show();
SomeOtherFunction();
}
I would also advise using the #Html.DropdownFor helper for your dropdowns.
I got some JQuery code that hides elements on my page. However I would like to keep showing the visible element when a page_load event has appeared.
Im using cshtml(razor) code, and in there I have a IsPost call, and I was wondering if a call to the JQuery .hide was possible.
The JQuery code:
<script>
$().ready(function () {
$(".btn").click(function () {
$(".Hide").hide("fast");
$("#" + $(this).data('type')).show("fast");
});
});
</script>
The C# code:
if(IsPost)
{
if(Request["btn"] == "btn1")
{
// Do some code
}
if(Request["btn"] == "btn2")
{
// Do some other code
}
}
The html code:
<div id="button1" class="Hide">
<form action="" method="post">
<input type="submit" name="btn" value="btn1" />
</form>
</div>
<div id="button2" class="Hide">
<form action="" method="post">
<input type="submit" name="btn" value="btn2" />
</form>
</div>
The answer I finally used looks like this:
<script>
$().ready(function () {
$(".btn").click(function () {
$(".Hide").hide("fast");
$("#" + $(this).data('type')).show("fast");
});
#{
if(IsPost)
{
<text>
$("#btn1).show("fast");
</text>
}
}
});
</script>