form.valid() not working from .js file in MVC - asp.net-mvc

I have a .js file which is called on mvc form submit click. In that .js file function I am trying to validate the form before I do ajax post to my controller
I have also referred following script files at top of .js files as below: -
/// <reference path="~/Scripts/jquery-1.9.1.js" />
/// <reference path="~/Scripts/jquery-ui-1.10.0.js" />
/// <reference path="~/Scripts/jquery.unobtrusive-ajax.js" />
/// <reference path="~/Scripts/jquery.validate.js" />
/// <reference path="~/Scripts/jquery.validate.unobtrusive.js" />
save = function() {
var form = $("#formID");
var result1 = $("#formID").validate();
var result = $("#formID").valid();
if (result === true) {
$.ajax({
url: whatever the url,
data: form.serialize(),
type: 'POST',
...............
..........
});
}
}
My View is strongly typed and model class have all DataAnnotations.
In my scenario I have a form which loads with all data initially and hten I am trying to clear all required field data and trying to submit so that I can see the validation. When form loads I can see the html with all data- atributes such as below.
<input class="custom" data-val="true" data-val-required="First Name is required." id="txtFirstName" name="Form1[0].FirstName" placeholder="First Name" title="First Name" type="text" value="robert">
I always get 'result === true' and thats why it goes for ajax post to controller and it breaks.( i will have server side validation in future to avoid this )
Surprisingly even after I have cleared the data from "First Name" field I still see value="robert" in there....is that an issue ?
I am not sure why this is not working.

1 Firsty use "Chrome Developer Tool(CDT)" for debugging client side
2 Put a break point on the line mentioned below
3 Then in CDT put the below code, it will show you what is the field, and the validation that is failing
**$.data($('form')[0], 'validator').errorList**
[
Object
element: input#FirstName.text-box single-line input-validation-error
message: "The FirstName field is required."
__proto__: Object
Working code below
$(function () {
// Handler for .ready() called.
$('#mycustomsubmitbutton').click(function () {
var $form = $('form').first();
var result = $form.valid();
// Put you break point in the below if condition
if (result === true) {
alert("form valid");
} else {
alert("invalid form");
}
});
});
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
Employee
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<p>
<input id="mycustomsubmitbutton" type="button" value="Valid the form and make an Ajax request" />
</p>
</fieldset>
}

Quote OP:
"Surprisingly even after I have cleared the data from "First Name"
field I still see value="robert" in there....is that an issue ?"
<input class="custom" data-val="true"
data-val-required="First Name is required."
id="txtFirstName" name="Form1[0].FirstName"
placeholder="First Name"
title="First Name"
type="text"
value="robert">
value="robert" is your problem. Because of this attribute the field is not empty.
See: http://jsfiddle.net/M7skq/ and http://jsfiddle.net/JszxA/

Related

Knockout + Blueimp Fie upload

I'm trying to marry my knockout VM into Blueimp File Upload using ASP.NET MVC.
What i'm trying to achieve is:
bind form data with KO view model
upload a file along with the form data, on button click
in teh action, receive the form data as parameters, and access the file data in any possible way
It would also be desirable to upload multiple files
The sequence is as follows:
This is why I have so far:
HTML
<form action="/Test/Post" method="post" enctype="multipart/form-data">
<div>
<label for="Id" >Id</label>
<input data-bind="value: Id" class="text-box single-line"
data-val="true" data-val-number="The field Id must be a number."
data-val-required="The Id field is required." id="Id"
name="Id" type="number" value="" />
</div>
<div>
<label for="ImageUpload">Image Upload</label>
<input id="ImageUpload" name="ImageUpload" type="file" value="" />
</div>
</form>
<button type="submit" data-bind="click: upload">Create</button>
<script>
$(document).ready(function() {
ko.applyBindings(new myVm({Id: 0, Something: 0}));
});
</script>
FileUpload Init
$('input:file').fileupload({
dataType: 'json',
autoUpload: false, // do not auto upload on file select
});
KO Script
function myVm(data) {
var self = this;
// Write mapping config
var mappingConfig = {};
// Perform mapping
ko.mapping.fromJS(data, mappingConfig, self);
// Upload
self.upload = function () {
$('#ImageUpload').bind('fileuploadsubmit', function (e, data) {
// Bind JS form
data.formData = ko.mapping.toJS(self);
});
// this doesn't trigger the binding to fileuploadsubmit
$('form').submit();
};
};

Submitting a form to ASP.NET MVC from Knockout does not bring in all the values

Here is what I have in my view in ASP.NET MVC 5
#model Entities.Coupon
#using (Html.BeginForm("coupon", "marketing", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="scsm-18 scmd-16 sclg-14">
<div class="form-group">
<label>Codes</label>
#Html.TextBoxFor(p => p.Code, new { #class = "form-control", #data_bind = "value: Code", #autofocus = true, #maxlength = "50" })
</div>
<input type="radio" name="IsPerCentOrDollar" value="1" data-bind="checked: IsPerCentOrDollar" />
<span>PercentageAmount</span>
<input type="radio" name="IsPerCentOrDollar" value="2" data-bind="checked: IsPerCentOrDollar" />
<span>DollarAmount</span>
<input type="radio" name="IsPerCentOrDollar" value="3" data-bind="checked: IsPerCentOrDollar" />
<span>FreeShipping</span>
</div>
<div class="panel-footer text-right">
<input type="submit" name="commandType" id="btnSave" class="btn btn-primary" data-bind="click:submit" value="Save" />
</div>
}
In the script:
$(document).ready(function () {
var viewModel = new CouponViewModel(couponModel);
ko.applyBindings(viewModel);
function CouponViewModel(data) {
self.Code = ko.observable(data.Code);
self.IsPerCentOrDollar = ko.observable("1");
self.DiscountLevel = ko.computed(function () {
return self.IsPerCentOrDollar();
});
};
}
Code in MVC:
[HttpPost, ActionName("coupon")]
public ActionResult coupon(Coupon coupon)
{
try
{
// some logic not yet in
}
catch (Exception ex)
{
}
return View();
}
That's all I have in there now.
In Developer tools inside the browser I can see values for self.DiscountLevel change on the selection of radio buttons.
On Submit, at MVC front the value of Code comes in but the values for DiscountLevel are not.
Any help is greatly appreciated.
Regards.
Let me expand on #StephenMuecke's comment (which has the gist of it I think).
ASP.NET MVC's default model binding will fill the argument (Coupon) with values found in the request. Only form elements are sent along with the request. You seem to expect that DiscountLevel is sent along, but it's just a JavaScript function that exists in the user's browser.
Adding something like this may solve your immediate problem:
<input type="hidden" name="DiscountLevel" data-bind="value: DiscountLevel" />
To note a related issue though: the property you have trouble with is a computed observable. However, you probably do not want to send it along as it depends entirely on IsPerCentOrDollar. Just have your server side Coupon class derive the discount level from that property too. That would also prevent users from hacking the hidden input and sending in a malicious value.

Can't route my input parameters to my controller action method

I'm having trouble passing my textbox data to a controllers action parameters.
I'm trying to get the url to look like:
http://localhost:51124/gifts?searchTerm=test
but when I enter in text into the text box I get a url that looks like:
http://localhost:51124/gifts
Here is the code I have for the route:
routes.MapRoute("Gifts",
"gifts",
new { controller = "Gifts", action = "Search" });
here is the code for the page with the text box and button to submit the text box data:
<form method="GET">
<input type="search" name="searchTerm"/>
<input type="button" value="Search By Category" onclick="location.href='#Url.Action("Search", "Gifts")'" />
</form>
here is the code for the controller that I'm trying to pass data to unsuccessfully:
public ActionResult Search(string searchTerm = null)
{
var model = db.Gifts.ToList();
return View(model);
}
"searchTerm" never gets any parameter that I pass into the text box. It's always null.
Create a form element in you view with an input (i.e. the search box) that has a name attribute matching the parameter and a submit button.
#using (Html.BeginForm("Search", "Gifts") {
<input type='text' name='searchTerm' value='' />
<input type='submit' value='search' />
}
This will post back to the Search method in the Gifts controller, passing the vale of the search box to the parameter 'searchTerm'
you have to build this with jquery. add a class to the inputs to use as a selector
<input type="search" name="searchTerm" class="txtSearch" />
<input type="button" value="Search By Category" class="btnSearch" />
then in your script
$('.btnSearch').on('click', function(){
var url = '#Url.Action("Search", "Gifts", new { searchTerm = "----" })'.replace("----", $('.txtSearch').val());
window.location(url);
});

Issue with multiple forms on one page: button submits the wrong form

I am writing a website version of a part of our windows application. It's basicaly a calendar. People can view Appointments and edit them. For every Appointment i have a form wich is hidden an will only be shown when a user clicks a link. Now the problem is only the form of the first appointment on a page works. If I click the submit button of another form it will actually submit the first form. Here's is the code generating the form:
<div class="popupbox" id="popuprel#{#mit.Id_mit}_#{#day.Day}">
#for (int i = 0; i < tcsForDay.Count; i++)
{
<p>
#tcsForDay[i].Tag_child.Zeitvo - #tcsForDay[i].Tag_child.Zeitna <br />
#if (tcsForDay[i].Subtype != null)
{
#:( #tcsForDay[i].Subtype.Type) #tcsForDay[i].Tag_child.Text
Editieren
}
else
{
#:( #Model.typeTagesEinteilung.Type) #tcsForDay[i].Tag_child.Text
Edit
}
</p>
<div id="AppForm#{#mit.Id_mit}_#{#day.Day}_#{#i}"class="AppForm">
#{
string formname = String.Format("AppFormForm{0}_{1}_{2}", mit.Id_mit, day.Day, i);
}
#using (Html.BeginForm("Index", "Plan", FormMethod.Post, new { #class = "AppFormForm", name = formname }))
{
#Html.Hidden("tagchild_id", tcsForDay[i].Tag_child.Id_tagchild);
#Html.Label("Text")<br />
#Html.TextBox("Text", null, new { #class = "required" })<br />
#Html.Label("Zeit Von")<br />
#Html.TextBox("ZeitVon", null, new { #class = "required time" })<br />
#Html.Label("Zeit Nach")<br />
#Html.TextBox("ZeitNach", null, new { #class = "required time" })<br />
<input type="submit" value="Speichern" name="button#{#mit.Id_mit}_#{#day.Day}_#{#i}" />
}
</div>
}
The names may not be obvious. tc or Tag_child is an appointment
When you look at the markup for each individual form what do you see?
My guess is that each HTML element is not getting a unique name. If this is the case, then it will never submit the proper form, because it doesn't know the difference between them.
Each form element on your page needs to have a UNIQUE name:
<input id="Text1" name="Text1" />
<input id="Text2" name="Text2" />
etc.

CheckBOX ASP MVC

Hi i am new to ASP.NET MVC. I am not sure how to deal with Check box or Radio Button to get values when they are clicked. Can any one help me? I am providing a simple code that might help you understand what i meant to be. Please share examples.
<script type="text/javascript" >
function check(browser)
{
document.getElementById("answer").value=browser;
} </script>
<form action="">
<input type="radio" name="browser"
onclick="check(this.value)"
value="Internet Explorer"/>Internet
Explorer<br />
<input type="radio" name="browser"
onclick="check(this.value)"
value="Firefox"/>Firefox<br />
<input type="radio" name="browser"
onclick="check(this.value)"
value="Netscape"/>Netscape<br />
<input type="radio" name="browser"
onclick="check(this.value)"
value="Opera"/>Opera<br />
<br />
Your favorite browser is: <input type="text" id="answer"
size="20"/> </form>
controller code
public ActionResult Index()
{
ViewData["list"] = new[]
{
new SelectListItem {Text = "InternetExplorer", Value = "InternetExplorer"},
new SelectListItem {Text = "Firefox", Value = "Firefox"},
new SelectListItem {Text = "Safari", Value = "Safari"},
new SelectListItem {Text = "Opera", Value = "Opera"}
};
return View();
}
[AcceptVerbs(HttpVerbs.Post),ActionName("Index")]
public ActionResult IndexPost(string browser)
{
// ...
}
view code
<% using (Html.BeginForm()) { %>
<% foreach(var item in (IEnumerable<SelectListItem>)ViewData["list"]) { %>
<label>
<% = Html.RadioButton("browser", item.Value) %>
<% = item.Text %></label>
<% } %>
<input type="submit" value="Select" />
<% } %>
<script type="text/javascript" src="<% = Url.Content("~/Scripts/jquery-1.3.2.js") %>" ></script>
<script type="text/javascript">
$(function() {
$("form:first").submit(function(e) {
e.preventDefault();
alert($(this).find(":radio:checked").val());
});
});
</script>
If you want browser value in action, you coding in IndexPost method.
or you want in javascript, onsubmit or onclick(and other) event handling, get checked radiobutton value at jQuery.
This was logic taken from: http://byatool.com/mvc/asp-net-mvc-how-to-handle-multiple-checkboxes-with-viewsactions-jquery-too/. I simply modified it very minimally.
----------
HTML Part|
----------
{form action="/Test/CheckForIds/" method="post"}
{div}
{input type="checkbox" name="IdList" value="1" /}
{input type="checkbox" name="IdList" value="2" /}
{input type="checkbox" name="IdList" value="3" /}
{input type="checkbox" name="IdList" value="4" /}
{/div}
{div}
{input type="submit" value="go" /}
{/div}
{/form}
----------------
Controller Part|
----------------
{AcceptVerbs(HttpVerbs.Post)} _
Function GroupPageSend(ByVal selectedObjects() As String) As ActionResult
{!--- YOUR CODE GOES HERE ---}
EX//
For Each item In selectedObjects
If i = 0 Then
string = Trim(item)
i = i + 1
Else
string = string & "," & Trim(item)
End If
Next
End Function
The above will gather values from selected checkboxes and will allow you to manage results.
Keep in mind all { = < and all } = >
I am probably not getting your question, but your sample will work well.
When you submit the form and the controller's method is called asp.net mvc will set the "browser" parameter to the value of the selected radio button's value.
hai friend try this,
<asp:RadioButton ID="RadioButton1" runat="server" onmousedown="yourjsfunc();" />

Resources