retrieve the model property value - javascript

I have following form
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.LabelFor(model => model.Product_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Product_ID, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
I want to get this model properties using jquery or javascript
for that I just followed approach like below
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.LabelFor(model => model.Product_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Product_ID, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
<div id="testid" class="col-md-offset-2 col-md-10" >
<input type="button" value="Test" class="btn btn-default" />
</div>
</div>
}
then in javascipt
<script type="text/javascript">
$(document).ready(function () {
var sampleID;
$("#Product_ID").keyup(function () {
sampleID = $('#Product_ID').val();
});
$('#testid').click(function () {
alert(sampleID);
});
});
</script>
But seems like this is not optimum approach me , keyup
appreciate if can suggest good way to get these values once after courser out

You can get value of #Product_ID in click event of #testid using $('#Product_ID').val() like below.
$('#testid').click(function () {
alert($('#Product_ID').val());
});

Since you are using razor then you can use # to get it directly in jquery like so:
$(function() {
var sampleID = "#Model.Product_ID";
});

The model is server-side only. If you need to do something with the values in the view, you handle it as if it's a regular HTML page and javascript.
If you want to grab the value of an input field, use the blur event that is triggered when focus is lost.
$("#Product_ID").blur(function() {
alert( "Handler for .blur() called." );
});

It looks like a typo in your JS. change kepup it to keyup.
This should work as expected.
$("#Product_ID").keyup(function () {
sampleID = $('#Product_ID').val();alert(sampleID);
//or you can use
alert($(this).val());
});

Related

MVC form Value not passed to JavaScript when using bootstrap to hide and show field

I am trying to passed the value from the MVC form to JavaScript. I am using bootstrap to hide and show field. when I remove the bootstrap hide and show functionality on the form I will get the value in the message box but when the Hide/Show is enable I cannot get the value as shown by the image below. can anyowne tell me where I am going wrong
HTML
#using (Html.BeginForm("SearchPatient","HOME", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Search Criteria", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SearchCriteria,
new List<SelectListItem> {
new SelectListItem { Value = "" , Text = "Select Search Criteria" },
new SelectListItem { Value = "1" , Text = "Patient Id" },
}, new { #class = "form-control selectchosen" })
</div>
</div>
<div class="form-group" id="PatientId" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.PatientId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientId, new { htmlAttributes = new { #class = "form-control " } })
</div>
</div>
</div>
<div class="form-group" id="AllShow" style="display:none">
<div class="form-group">
<div class="col-lg-offset-2">
<input type="button" value="Search" class="btn btn-success" id="btnSubmit" onclick="Enablecontrols();" />
</div>
</div>
</div>
</div>
}
JavaScript
<script type="text/javascript">
$('#SearchCriteria').change(function () {
if ($("#SearchCriteria").val() == 1) {
$("#AllShow").show();
$("#PatientId").show();
ValidateField("PatientId", true);
}
function Enablecontrols() {
$(document).ready(function () {
var patientid = $("#PatientId").val();
if ($("#SearchCriteria").val() == 1) {
alert("I am an alert box! the patient number is" + patientid);
}
}
}
</script>
rather than use the show/hide methods of bootstrap, use toggle. It's more reliable.
If that doesn't work you can also use $('#PatientId').css('display','block');
Issue fixed by changing the ID of the Div to dPatientId
Stupid mistake

Call JS method from Razor form submit

When I submit the form I want to fire-up the Javascript method written below. This JS method will send a POST request to the backend. However, in the code written below this JS method is not being fired. Can someone please help me how to correct this ?
#using (Html.BeginForm(null, null, FormMethod.Post, new { #class = "form-horizontal", onsubmit = "submitdata" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.EMAIL, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.email, new {id ="Email", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.pwd, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.pwd, new {id="pwd", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" onsubmit="submitdata"/>
</div>
</div>
}
Javascript
function submitdata() {
var pwd = document.getElementById("pwd");
var email = document.getElementById("email");
$.ajax({
type: 'post',
url: '/Account/Reg',
data: {
email: email,
password: pwd
},
success: function (response) {
$('#success__para').html("You data will be saved");
}
});
return false;
}
You miss () in your onsubmit attribute;
onsubmit = "submitdata()"
As Vostrugin mentioned in his answer, you are missing () in the method call.
Here is the unobtrusive javascript way (using jQuery)
function submitdata() {
// your existing code
}
$(function(){
$("form").submit(function(e){
e.preventDefault();
submitData();
});
});
If you want to wire it with a specific button click, use a jQuery selector to get the button and bind the click event.
<input type="submit" id="myButton" value="Register"/>
and
$(function(){
$("#myButton").click(function(e){
e.preventDefault();
submitData();
});
});
With this approach, you should remove the onsubmit event from your UI markup.

Remove cloned div one by one from last but not the default one using jquery in MVC 5

My default view is this.
Add button is working as expected but when I try to remove the cloned div I am only able to remove the last one but not all the cloned div one by one from last expect the default one.
Here is my Div and Jquery to add and remove div.
Add:
$("#AddSubService").click(function(){
$("#SubServices").append($('#SubServiceName').clone(true).find("input").val("").end());
$("#SubServices").append($('#SubServiceDescription').clone(true).find("input").val("").end());
});
Remove:
$("#RemoveSubService").click(function(e){
$("#SubServices").children("div[id=SubServiceDescription]:last").fadeOut();
$("#SubServices").children("div[id=SubServiceName]:last").fadeOut();
});
Div:
<div id="SubServices">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<h2>Sub Services</h2>
<input type="button" value="Add" class="btn btn-default" id="AddSubService" /> |
<input type="button" value="Remove" class="btn btn-default" id="RemoveSubService" />
</div>
</div>
<div class="form-group" id="SubServiceName">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="SubServiceDescription">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
As I am pretty new in MVC and Jquery so any right direction to achieve the same would be highly appreciable.
Use below script function to remove cloned divs
$("#RemoveSubService").click(function (e) {
var divCount = $("#SubServices").children("div[id=SubServiceDescription]").length;
while (divCount > 1) // comparing with 1 beacuse: It will keep default div and remove rest
{
$("#SubServices").children("div[id=SubServiceDescription]:last").remove();
$("#SubServices").children("div[id=SubServiceName]:last").remove();
divCount--;
}
});
This is not happening correct because of id attribute, id attribute should always be unique in html that'w why, use class instead of.
$(document).ready(function() {
$('.AddNew').click(function() {
$(".TargetElements:first").clone().insertAfter('.TargetElements:last');
$('.Remove').show();
});
});
$(document).ready(function () {
$('.Remove').click(function () {
if ($(".TargetElements").length > 1) {
$(".TargetElements:last").remove();
}
else {
$('.Remove').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="TargetElements">
<label>Name</label> </div>
<div>
<input type="button" value="Add" class="AddNew" />
<input type="button" value="Remove" class="Remove" hidden="hidden" />
</div>
<div class="TargetElements">
<label>Name</label>
</div>
<div> <input type="button" value="Add New Language" class="AddNew" />
<input type="button" value="Remove" class="Remove" hidden="hidden" />
</div>
<script>
$(document).ready(function () {
$('.AddNew').click(function () {
$(".TargetElements:first").clone().insertAfter('.TargetElements:last');
$('.Remove').show();
});
});
</script>
<script>
$(document).ready(function () {
$('.Remove').click(function () {
if ($(".TargetElements").length > 1) {
$(".TargetElements:last").remove();
}
else {
$('.Remove').hide();
}
});
});
</script>

Form serialization always returns empty string

I have a dropdown in my view. Based on the selection, i insert a partial view into a div (placeholder) in view. Below is the View.
<div class="container">
<div class="row">
<div class="col-lg-4"><p class="lead">What do you want to do?</p></div>
<div class="col-lg-8">
<select id="myDropDown">
<option id="0" selected>I want to..</option>
<option id="1">Reset my password</option>
</select>
</div>
</div>
<div id="partialPlaceHolder" style="display:none;"> </div>
<script type="text/javascript">
$(document).ready(function () {
$('#myDropDown').change(function () {
/* Get the selected value of dropdownlist */
var selectedID = $(this).find('option:selected').attr('id');
/* Request the partial view with .get request. */
$.get('/Requests/FindPartial/' + selectedID, function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
So when I select, "Reset my password" in the dropdown, I am successfully inserting my partial view into the div in my view. Below is my partial view.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-12">
<div class="well well-lg" style="text-align:left">
<div class="form-horizontal" id="resetpasswordform">
<h4>Reset Password</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ServersList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ServerName, new SelectList(Model.ServersList))
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="submitButton" value="Reset" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
}
<script>
$(function () {
$("#submitButton").click(function () {
debugger;
$.ajax({
type: "POST",
url: "Requests/Do_ResetPassword",
data: $("#resetpasswordform").serialize(),
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
});
});
</script>
The problem is when the submit button is clicked, and I make the ajax post call, the $("#resetpasswordform").serialize() is always "" (empty string).
I tried making the view just with one element. I verified that the elements have name attribute for serialize to work. I also confirmed that I don't have a type=submit in my button. I changed the resetpasswordform into a form instead of div. I even rendered the partial view directly in Index.cshtml without dynamically populating. Nothing fixed the problem. All the time it returns empty string.
I verified all other similar questions in SO and not getting any hint on what i am doing wrong. Please help.
How about you set the id in the form tag:
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { Id = "resetpasswordform" }))
and remove it from the div.

Moving the submit button outside the form in MVC 5 with Partial view

In MVC 5,
I have a Dialog for editing.
The Content area is created from a Partial view.
If I have the submit button inside the form in the Partial view it works. But I would like the Save button to be at the button of the Dialog and hence outside the form and Partial view.
The problem is now that the forms data doesn't get posted. How would you fix this?
I have two ideas:
1) Wrap the form outside the Partial view
2) Make a AJAX request and not use the helper, and collect the data from the form somehow? Doesn't feel like the right way.
Dialog:
<div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit database connection</h4>
</div>
<div class="modal-body">
#{ Html.RenderPartial("View"); }
</div>
<div class="modal-footer">
<button id="saveBtnSettings" type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Dialog javascript
var saveSettings = function () {
var url = buildUrl("Edit", "Setting");
$.ajax({
type: "POST",
url: url
})
.done(function (data, textStatus, jqXhr) {
alert('done' + data);
})
.fail(function (jqXhr, textStatus, errorThrown) {
alert(textStatus.toUpperCase() + ": " + errorThrown + 'Could not load html. ');
});
};
Partial view
#using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }))
{
<fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.User, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataSource, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataSource, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DataSource, "", new { #class = "text-danger" })
</div>
</div>
</div>
</fieldset>
}
Partial view - Works with button inside of the form
#using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }))
{
<fieldset>
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.User, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataSource, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataSource, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DataSource, "", new { #class = "text-danger" })
</div>
</div>
<p>
<input type="submit" value="Calculate" /> #* WORKS WITH BUTTON INSIDE OF FORM *#
</p>
</div>
</fieldset>
}
You can place a submit button outside the form tags by specifying the form attribute (HTML5 only)
<form .... id="editform">
....
</form>
<input type="submit" form="editform" />
Note if the submit button has a value attribute, it won't be posted back.
Another option may be to use css to position it.
Just submit the form using Javascript:
function SubmitMyForm(){
document.getElementById("myForm").submit();
}
HTML:
<input type="button" value="Calculate" onclick="SubmitMyForm()" />
I think you're looking for: document.myform.submit();
Here is a Fiddle adapted form of code from this page.

Categories