asp.net mvc 5 date picker in form without any model - asp.net

inside the page which is belong to other model and here I need only one input which should have date picker. I don't want I select type in model but here in html, is there any helper or library?

You just have to add required jQuery files or libraries as below for jQuery DatePicker: (If you are using bundling in ASP.NET MVC, then use the following. By the way, bundling means to add all jQuery or CSS files in a single class for optimization)
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css",
"~/Content/jquery-ui.css"));
Or simply without bundling, you can do the following as well:
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
In the head section:
<script >
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
Then finally:
<p>Date: <input type="text" id="datepicker" /></p>
For more, you can check the below links:
Sample-jQuery-DatePicker-01
jQuery-Plugin-Samples
Sample-jQuery-DatePicker-02

Related

Using Jquery-fileupload plugin without the <form> tag?

I'm trying to integrate Jquery File Upload plugin in my aspx page (asp.net website). I followed the guide, including all required scripts and stylesheets, but in the index.html it's used a form tag to initialize the plugin and with the tag are also specified action and method attributes. Since I'm using asp.net, I am not allowed to insert the form tag because asp.net wrap the whole website with another form tag and it doesn't allow to insert another form tag inside it.
How can I initialize the plugin in a different way?
You don't actually have to have a form to use jQuery file upload plugin. Because the plugin is using jQuery ajax under the hood. use the bellow code inside your page, keep in mind you have to code an API on the server side.
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = 'your server api or handler';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
and your html as follows:
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Select files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>

asp.net mvc javascript postback

I'm mixing asp.net webforms and asp.net-mvc. To use webforms I've included
routes.IgnoreRoute("Reports/{*pathInfo}");
in the public static void RegisterRoutes(RouteCollection routes) method.
It seems to work just fine. But javascript postbacks on the asp.net webform pages don't work. Specifically
<script type="text/javascript">
function callMethod(methodName, methodArgument)
{
alert('test1');
document.getElementById("methodname").value=methodName;
document.getElementById("methodargument").value=methodArgument;
alert('test2');
document.forms[0].submit();
}
</script>
doesn't work. Everything is fine until the document.forms[0].submit(); call which appears to do nothing. If I completely disable the asp.net MVC route mapping then the above Javascript works just fine.
I just completed a brand new sample project and was able to get this to work... I created a folder in the root of my project called Reports and added the Billing.aspx page there. I then added the code below to the default Index view within the Home folder as shown below.
Global.asax
routes.IgnoreRoute("Reports/{*pathInfo}");
MVC Page Views\Home\Index.aspx
<form method="post" action="../../Reports/Billing.aspx?tenantId=0003-0140&rentNum=0" id="myForm">
<input type="text" id="sample" /><br />
<input type="button" onclick="callMethod();" value="send" />
</form>
<script type="text/javascript">
function callMethod()
{
alert('test1');
alert(document.getElementById("sample").value);
alert('test2');
document.forms[0].submit();
}
</script>
My guess is that even though your form's action is set to Billing.aspx, it is not looking for it in the correct folder. Try adding "../../Reports/" in front of Billing.aspx to your form's action. Since the Billing page is not in the same root as the MVC page, that is likely to not go anywhere on a post action...

Error occurs when jQuery processing a form is inside another form

I am writing a form using jQuery and encounter some difficulties.
My form works fine in static page (html).
However, when I use the form in dynamic page(aspx), the form does not behave correctly.
I cannot append items to the form and call the form.serialize function.
I think the error occurs when a form is inside another form (.aspx code needs to enclosed by a form tag).
What should I do?
Let me give a simplified version of my code:
<form name="Form1" method="post" id="Form1">
some content
<form name="form_inside">
<input name="fname" type="text" />
</form>
</form>
jQuery code:
$("#form_inside").append($("<input type='text' name='lname'>"));
When the user submits,
$("#form_inside").serialize();
// it should return fname=inputfname&lname=inputlname
I want to append element to "form_inside" and serialize the form "form_inside".
The form "Form1" is required by the aspx and I cannot remove it.
Could you just serialize the fields inside Form1?
I don't know anything about ASP, but it seems that you're not doing a straightforward "submit" anyway - so does it really matter if the fields aren't within their own separate form?
You could possibly group the fields you're interested in within a <div> or something, e.g.:
<div id="my-interesting-fields">
...
</div>
then substitute #form-inside with #my-interesting-fields where appropriate - is that helpful at all?
Edit
OK, a quick glance at the jQuery code suggests that serialize() depends on the form's elements member.
I suppose you could hack this in a couple of different ways:
Copy all elements from #my-interesting-fields into a temporary <form> that you dynamically create outside Form1, then call serialize() on that. Something like:
$("#Form1").after("<form id='tmp-form'></form>").
append("#my-interesting-fields input");
$("tmp-form").serialize();
Or, create an elements member on #my-interesting-fields, e.g.
$("#my-interesting-fields").elements = $("#my-interesting-fields input");
$("#my-interesting-fields").serialize();
I haven't tried either of these, but that might give you a couple of ideas. Not that I would necessarily recommend either of them :)
Because you can't have nested <form> tags you'll need to close off the standard dotnet form tag like below:
<script type="text/javascript">
$(document).ready(function() {
$("#form_inside").append($("<input type='text' name='lname'>"));
$("#submitBtn").click(function() {function() {
var obj = $("#form_inside *");
var values = new Array();
obj.each(function(i,obj1) {
if (obj1.name && !obj1.disabled && obj1.value) {
values.push(obj1);
};
});
alert(jQuery.param(values));
}); });
});
</script>
<form id="form1" runat="server">
<div>
<div id="form_inside" name="form_inside"> <input name="fname" type="text" /><input type="button" id="submitBtn" /></div>
</div>
</form>
jQuery.param on a array of form elements will give you the same results as .serialize()
so you get all elements in div $("#form_inside *) then filter for elements then on the result jQuery.param will give you exactly what you need

JQuery validate dynamically add rules

I am currently using the validate plugin to validate a form (using ASP.Net controls). I have stripped out the rules from the standard setup within the form.validate method ie:
$("form").validate({
rules: {
ctl00$ContentPlaceHolder1$dgQuestions$ctl14$iRadList_Col0: "required"
}
});
I now have these in various functions which add the ruless depending on what button is clicked. This works fine for text boxes, but for a RadiobuttonList when the plugin tries to add the rule there is an error saying the element is undefined.
function addRuleSet() {
$("#ctl00$ContentPlaceHolder1$dgQuestions$ctl14$iRadList_Col0").rules("add", { required: true });
}
I think the problem is that I am using the name attribute (asp puts $ in )to define the group that the radio buttons belong to rather than an id (, but in the static settings all the elements are definied using the name attribute. Anyway I am not sure how to get around adding a rule for a group of associated radio buttons, any advice would be appreciated.
PS I really need to call the RadioButtonList rather than the individual radio buttons.
You can also apply a rule by setting classes on the element. For example, if you give the class "required" to an input, then the required rule applies to that element. To do this, you'd use the CssClass property on the control. You may need to experiment with compound controls, like RadioButtonList, to make sure that the class is being applied to the input elements generated, not the container. If you have trouble with this, one way to do it would be to add the class using jQuery after the page loads based on a selector.
<asp:RadioButtonList id="RadList" runat="server" CssClass="required">
...
</asp:RadioButtonList>
or
<script type="text/javascript">
$(function() {
$(':radio').addClass('required');
$('form').validate();
});
</script>
For a complex, class-based rule you can add new rules using addClassRules.
<script type="text/javascript">
$(function() {
$.validator.addClassRules({
range0to10: {
range: [0, 10]
},
name: {
minlength: 2,
required: true
}
});
$('form').validate();
});
</script>
<form ... >
<input type="text" name="rating" id="rating" class="range0to10" />
<input type="text" name="firstName" id="firstName" class="name" />
<input type="text" name="lastName" id="lastName" class="name" />
</form>
After days of this driving me mad, asking the question got me thinking how to get the element returning properly, and I came across this method of referencing staright away which allows me to do it:
$("input:radio[name='ctl00$ContentPlaceHolder1$dgQuestions$ctl14$iRadList_Col0']").rules("add", { required: true });

Using embedded standard HTML forms with ASP.NET

I have a standard aspx page with which I need to add another standard HTML form into and have it submit to another location (external site), however whenever I press the submit button the page seems to do a post back rather than using the sub-forms action url.
A mock up of what the form relationships is below. Note in the real deployment the form will be part of a content area of a master page layout, so the form needs to submit independantly from the master page form.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<form id="subscribe_form" method="post" action="https://someothersite.com" name="em_subscribe_form" >
<input type="text" id="field1" name="field1" />
<input id="submitsubform" type="submit" value="Submit" />
</form>
</div>
</form>
</body>
</html>
It's an interesting problem. Ideally you only want the 1 form tag on the page as other users have mentioned. Potentially you could post the data via javascript without having 2 form tags.
Example taken from here, modified for your needs. Not 100% sure if this will work for you but I think this is how you'll have to approach it.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function postdata()
{
var fieldValue = document.getElementById("field1").value;
postwith("http://someothersite.com",{field1:fieldValue});
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<input type="text" id="field1" name="field1" />
<asp:Button ID="btnSubmitSubscribe" runat="server" Text="Submit" OnClientClick="postdata(); return false;" />
</div>
</div>
</form>
</body>
</html>
If javascript is not a viable option - you can use .Net's HttpWebRequest object to create the post call in code behind. Would look something like this in the code behind (assuming your text field is an asp textbox:
private void OnSubscribeClick(object sender, System.EventArgs e)
{
string field1 = Field1.Text;
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="field1="+field1 ;
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://someotherwebsite/");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
}
If you add an ASP.NET button to the form, and set its PostBackUrl property to the external site, then all the form data will be posted to that URL.
There is a very nice tricky solution for this problem.
You can insert a </form> tag before your <form> to close the asp.net form which causes the problem. Do not forget to add a <form> tag after your html form. It may cause the editor to give you an exception, but do not worry, it will work.
Nested forms are not possible in HTML according to the W3C. You can achieve your intended result using JavaScript or with jQuery as explained by Peter on a blog called My Thoughts.
In my experience, Appetere Web Solutions has the best solution. Simple and elegant...and it's not a hack. Use the PostBackUrl.
I just tried it and everything works as expected. I didn't want to use Javascript because I didn't want to include it in my Master Page for every page that uses it.
I had the same situation as Ross - except that my input types were all of the "hidden" varitey.
Cowgod's answer got me thinking about nested forms within my .aspx page. I ended up "un-nesting" my 2nd form OUT of the main .aspx form ( ) and placed it (along with my js script tags) just under the body tag - but before the main .aspx form tag.
Suddenly, everything was submitting as it was supposed to. Is this a hack?
ASP.NET allows you to have multiple forms on one page, but only one can be runat=server. However I don't think you can nest forms at all.
You might have to make a new master page, one without a form tag on it so the form will work on that one page only. This is not a good solution, unless you can place the form outside the master pages' form, and use javascript to submit the second form, but that's hardly better. There really is no good solution for what you are trying to achieve, and if so I'd like to hear it. I don't think you can do a POST call from a code-behind, can you? I'm sure there's some way. But that's probably the only solution: from code.

Resources