Form serialization always returns empty string - javascript

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.

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

Set selected value of dropdowns from cookie

I have three dropdowns in my form, and I would like to not lose the data that the user has selected, even if I refresh or I navigate in other page and come back.
This is my view where I have the 3 dropdowns:
#using (Ajax.BeginForm("SearchForCars", "Home", null, new AjaxOptions { UpdateTargetId = "DivCategoriesTree", OnSuccess = "success", HttpMethod = "Post" }, new { make = "makes" }))
{
<div>
<div class="col-sm-4" style="height: 10em;display: flex;align-items: center ; padding-top:25px;">
<i class="fa fa-car" style="font-size:60px;color:red; padding-left:20px;"></i>
<strong style="padding-left:20px;">Vă rugăm să selectați vehiculul dumneavoastră!</strong>
</div>
<div class="col-sm-4">
<div style="padding-top:15px;">
<form class="form-control-static">
<div class="form-group">
<div class="row">
<div class="col-sm-10">
#if (ViewData.ContainsKey("makes"))
{
#Html.DropDownList("makes", ViewData["makes"] as List<SelectListItem>, "--Select car--", new { #class = "dropdown-toggle form-control" })
}
</div>
</div>
<div class="row">
<div class="col-sm-10">
<p></p>
#Html.DropDownList("models", new SelectList(string.Empty, "Value", "Text"), "--Select model--", new { #class = "dropdown-toggle form-control" })
</div>
</div>
<div class="row">
<p></p>
<div class="col-sm-10">
#Html.DropDownList("engines", new SelectList(string.Empty, "Value", "Text"), "--Select engine--", new { #class = "dropdown-toggle form-control" })
</div>
</div>
</div>
</form>
</div>
</div>
<div class="col-sm-4" style="height: 10em;display: flex;align-items: center ; padding-top:25px;">
<input type="submit" id="btnSearch" class="btn btn-default active" value="Cauta" disabled="disabled" style="width:150px;" />
</div>
</div>
}
</div>
Here are the 3 dropdowns:
I use cookies to store the data that the user has selected.
I tried to set the dropdown from the controller in this way:
public ActionResult Index()
{
var asa = HttpContext.Request.Cookies.Get("make_model_engine");
var model = asa.Values["model"].ToString();
var make = asa.Values["make"].ToString();
var makeList = new SelectList(makeRepository.GetMakes(), "ID", "Name");
ViewData["makes"] = makeList;
**var selected = makeList.Where(x => x.Value == make).First();
selected.Selected = true;**
return View();
}
Although it seems that the selected value is set correctly from cookies, it does not work, the dropdowns are not showing the selected value.
I guess that I should fix this in the view with javascript, but I'm new to javascript and I don't know what would be the best fix for this.
Can you please help me how can I resolve this?
Thank you!
You can pass the selected value you read from the cookie as the last parameter of the SelectList constructor:
var makeList = new SelectList(makeRepository.GetMakes(), "ID", "Name", make);

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.

retrieve the model property value

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());
});

Ajax script not working on Form Submit?

I have an issue, I am loading a partial page however I dont want the form on this page to redirect when I click the save button.
Not sure if I am using the script the correct way, I want to Post to the controller when I click submit but I want to be redirected back to the same page I was on (AdminPanel/AdminProfile) and not redirected to a different controller/view (Account/Manage).
AdminProfile View:
<div id="tab-2" class="tab-pane">
#{Html.RenderPartial("~/Views/Account/Manage.cshtml");
}
</div>
Not sure if my script should go in this view or stay in the partial view?
Controller:
public ActionResult Manage(LocalPasswordModel model)
{
//....
return Json(new { redirectTo = Url.Action("AdminProfile", "AdminPanel") });
}
Partialview with script:
#model LocalPasswordModel
#{
ViewBag.Title = "Change Password";
}
<section class="hgroup">
<div class="panel-body">
<ul class="breadcrumb pull-right top-right">
<li>You're logged in as <strong>#User.Identity.Name</strong></li>
</ul>
<ul class="message-success">#ViewBag.StatusMessage</ul>
#using (Html.BeginForm("Manage", "Account", FormMethod.Post, new { id = "SavePassword", #class = "form-horizontal" }))
{
<div class="social_sign">
<h3>Change your password.</h3>
</div>
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label class="col-sm-2 control-label">Old Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.OldPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.NewPassword, new { #class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col">
<input type="submit" class="btn btn-primary pull-right" value="Change password" />
</div>
</div>
}
</div>
</section>
Script in the view above:
#section Scripts {
<script>
$('#SavePassword').submit(function ()
{
if ($(this).valid())
{
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
if (result.redirectTo)
{
window.location.href = result.redirectTo;
}
else
{
$(".tab-2").html(result);
}
},
error: function ()
{
}
});
}
})
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Nothing seems to happen all I get is an empty page with {"redirectTo":"/AdminPanel/AdminProfile"} in it. Which is the url: http://localhost:57239/Account/Manage
you should change your code like these:
<script>
$('#SavePassword').submit(function ()
{
if ($(this).valid())
{
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
if (result.redirectTo)
{
window.location.href = result.redirectTo;
}
else
{
$(".tab-2").html(result);
}
},
error: function ()
{
}
});
}
return false;
})
</script>
You have already attached the AJAX call, but forgot to prevent the default submission event. So, use event.preventDefault():
$('#SavePassword').submit(function (e) {
e.preventDefault();
// Rest of your code.
if ($(this).valid())

Categories