use dynamically generated array (jquery) in code behind class - javascript

var data = $("#list2 li").map(function () { return $(this).children().html(); }).get();
the data variable contains the values that are fetched using jquery
can anyone suggest me the way how can i use this array in code behind class of the web page
on button .click event
my button is aspx control (runat ="server")
as
script type="text/javascript">
function eOrder() {
var data = $("#list1 li").map(function () { return $(this).children().html(); }).get();
debugger;
};
<div style="clear:both;"></div>
</div>
<asp:Button ID="btnSave" runat="server" Text="Save" />
the values in the list are generated dynam,ically on Page_Load method
li = new HtmlGenericControl("li");
div = new HtmlGenericControl("div");
div.InnerText = webpart.DisplayTitle;
li.Controls.Add(div);
list2.Controls.Add(li);
& the list is also runat= "server"
basically i need to send the data array in code behind class on btnSave click
thankx in advance

Simplest way is to add a HiddenField on your page and use jQuery to set its value to the string of the array. Then in code behind you use JSON deserializer to turn the string into an array of some type.
For deserialization you can use the JSON features provided by the .NET Framework: http://msdn.microsoft.com/en-us/library/bb412179.aspx
This is a bit more complex but does not add dependencies to your project.
Alternatively you can use the increasingly popular JSON.NET. It seems easier to use but is an additional dependecy to your project. You probably want to use it if you do a lot of JSON work serverside.

Think you could use Ajax here
jQuery.ajax

Related

Jquery and Ajax inside ASP.NET How to update div with model

In my app I am sending post request with string value with Jquery, then in controller, passed string value is used to get some data from API.
Next controller returns a view and model with data from API inside. That data from model I want to put inside values of few textboxes.
The main problem is that I dont know how to refresh that div with model values. When I used post form without jquery and ajax it works but I want to do it asynchronous.
Js script with post request:
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
var data1 = $('#textBox').val();
$.ajax({
url: '/Home/Fill',
type: 'POST',
dataType: 'string',
data: { number:data1 },
success: function (data) {
}
});
});
});
Controller:
[HttpPost]
public ActionResult Fill(string number)
{
CompanyInfo Info = new CompanyInfo();
//Here some API actions
return View("Index",Info);
}
Div with model values inside the Index view:
<div id="target">
<h1>Number:</h1>
<input type="text" value="#Html.DisplayFor(m => m.Num)" id="Number" />
<br />
<h1>Company name:</h1>
<input type="text" value="#Html.DisplayFor(m=>m.CompanyName)" id="CompanyName" />
<br />
<h1>Street Address</h1>
<input type="text" value="#Html.DisplayFor(m=>m.StreetAddress)" id="Address" />
</div>
At this point you're not really working with "views and models" in the ASP.NET MVC sense, you're simply working with JavaScript/jQuery to update your DOM. How you do that depends on the data you have and is done entirely in here:
success: function (data) {
}
So what's in data?
This implies that you have HTML in data, perhaps even an entire page:
return View("Index",Info);
If that's the case, you probably want to select out of data the information you want. Is it the same page that you're already showing? If so then you can just replace the HTML you already have with the HTML from the page. Perhaps something like this:
var newTarget = $('#target', data).html();
$('#target').html(newTarget);
That should grab the HTML of the div id="target" from data and then set it to that same div in the current page.
If the HTML in data is different from the current page, then you would need to target what you're doing differently of course. But ultimately it's the same concept. Be aware that a side-effect of replacing HTML elements in your page with new elements is that any event binding you had on the old elements is lost.
Note that this isn't the most efficient way to do this. Returning an entire page when all you need is an updated model includes a lot of overhead that you just end up ignoring anyway. This would be a good opportunity to look into using WebAPI controllers in your project, where you could return plain objects:
return Info;
Or even just returning a JsonResult from your MVC controller would do the trick:
return Json(Info);
That way the data variable in your client-side code doesn't contain all of this unnecessary HTML, but instead contains just the information in the Info object. With that, you can simply update the values of your input elements directly. Perhaps something like this:
$('#Number').val(data.Num);
$('#CompanyName').val(data.CompanyName);
$('#Address').val(data.StreetAddress);
It's up to you how you want to approach it. But you definitely have options and can do a good bit of refactoring to simplify things.
You need to use the success: function(data) listener inside your AJAX request. Get your data and parse it into the div.

How can I get the text from an Asp.Net TextBox control with Jquery or Javascript?

I have an Asp.Net TextBox control:
<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom"></asp:TextBox>
In a separate Jquery/Javascript file, I would like get the text from it... normally the text is like '9/1/2015'.
I have tried the following:
var r2FromDate = new Date($(".txtFromDate").val);
var r2FromDate = new Date($(".txtFromDate").val.toString());
var r2FromDate = new Date($(".txtFromDate").val());
var r2FromDate = new Date($(".txtFromDate").text());
var r2FromDate = new Date($(".txtFromDate").text);
and the same with using the # <%= txtFromDate.ClientID %> notation and it completely breaks with that.
Please help!
$('#txtFromDate').val();
You want to select using the ID, not the class.
var text = $("#<%=txtFromDate.ClientId %>").val();
ASP should then output the ID generated on the client and your javascript can select it. You can also reuse this variable instead of querying the DOM over and over [it has to find it every time you use jQuery like "$(...)"].
If your javascript is located in another file, you can use the name attribute instead
<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtDateFrom" name="txtFromDate"></asp:TextBox>
$('input[name="txtFromDate"]').val();
https://api.jquery.com/attribute-equals-selector/
Alternatively, you can define the following property on your TextBox
ClientIDMode="static"
That will ensure that your ID on the client side will be the same as the server side id.
And then you can use:
$('#txtFromDate').val();
It was actually because I put the id as 'txtFromDate' and the class as 'txtDateFrom' instead of keeping them the same. I was trying to access the class 'txtFromDate' when it didn't exist.
.val() works when you select the right class.
You can try this through this you can also get asp button or any control for that matter.
var txt_txtFromDate = document.querySelector("input[id*='txtFromDate']");
alert(txt_txtFromDate.Value);
you can also try querySelectorAll() if you have multiple controls with same id in client side.
Also, $("input[id*='txtFromDate']") will work.

Select partial ID name in javascript

I have an asp.net webform where I include the following script (on a separate .js file):
function pageLoad() {
var mpe = $find("mpeEmpresa");
mpe.add_shown(onShown);
$addHandler(document, "keydown", onKeyDown);
}
function onShown() {
var background = $find("mpeEmpresa")._backgroundElement;
background.onclick = function() {
$find("mpeEmpresa").hide();
}
}
Unfortunately, it won't work because asp.net 3.5 changes the elements id's. The only way I could get it to work is to use ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa as the ID.
Sure I could use <%= mpeEmpresa.ClientID %> from the asp.net side, it would work but I'll have to pass that as a var to my external .js file and it's not exactly what I'm trying to accomplish.
I have searched on a few ways to select the element by it's ID name partially, but couldn't get any of them to work... Is there a guaranteed way?
I can see the JQuery tag on your question, so you can easily use this:
$('div[id*="mpeEmpresa"]')
As i know the ContentPlaceHolders are rendered as div.
Update:
If you need to select empresaFilha too so you can't use the above selector.
because $('div[id*="mpeEmpresa"]') select both of ctl00_ContentPlaceHolder1_empresaFilha and ctl00_ContentPlaceHolder1_empresaFilha_mpeEmpresa.
so you need to use this:
Select only mpeEmpresa:
$('div[id*="mpeEmpresa"]').css("background-color","blue");
Select only empresaFilha:
$('div[id*="mpeEmpresa"]').parent('div[id*="empresaFilha"]').css("background-color","red");
Or something like this, maybe this code isn't so optimized because i don't see your ASP code or rendered HTML so have to provide a general solution.
You can simply use this
var mpe=$('div[id$="mpeEmpresa"]');
or
var mpe=$find('div[id$="mpeEmpresa"]');

How to put a javascript variable into view in mvc 4?

I know that is a small problem, but i didn't found any solution, so i have a javascript variable <script>
var coords = []; </script> and i want to put it in my view :
<input type="submit" name="Tracking" value="Tracking" data-coords="//here !!!"/>
so please if someone have any idea i will be very appreciate.
Method 1;
You Can use this code;
$("[name='Tracking']").attr("data-coords",coords);
Method 2;
if dont required use data-coords
you can use jquery .data()..
replace this;
<input type="submit" id="Tracking" name="Tracking" value="Tracking"/>
and
$("#Tracking").data("data-coords", coords);
You can handle it on the client side:
// javascript version
// safe, if you have only one element that has a name "Tracking"
var btn = document.getElementsByName("Tracking")[0].value;
var a = document.createAttribute('data-coords');
a.value = coords;
btn.setAttributeNode(a);
// or do it easier with jquery
$('[name="Tracking"]').attr('data-coords', coords);
If you want to set dynamic values to something in your HTML, you should use JavaScript to do it. The exact way of doing this depends on context - when exactly you want to set those values and what you want to do with them before.
If you want to set value of data-coords on DOM load and you use jQuery, write code that updates data-coords attribute of this input inside $(document).ready function. You can use attr function to do this if you use jQuery.

How to relate data (id's) to links for JavaScript?

I'm trying to write a fairly complex dynamic web page, using JQuery AJAX, and I am struggling with how to relate my links (<a ...>) with the the data their tied to, such as action names, and data element ids. I have pondered several different schemes, but I'm not sure I like any of them.
Building it into onclick, which means I have to configure it in the link generation.
<a onlick="func('abc', 123)">...</a>
Inserting it into the id of the link, which means parsing it out in JavaScript.
<a id="link_abc_123">...</a>
Putting the link in a div with hidden input elements...
<div>
<a>...</a>
<input type="hidden" name="action" value="abc"/>
<input type="hidden" name="id" value="123"/>
</div>
Is there a best practice or a commonly accepted way of structuring this data?
Best practice should always be, to strictly separate Code.
That means, you shouldn't include any Javascript into your backend-source code. So personally I'm a big fan of either putting the necesarry data into the elements (your last example) when using a template-engine, or sending just the necesarry data on a separate request (JSON for instance) to the client.
Using jQuery, it's a very convinient way to create data- attributes, where you can store any information, while jQuery will translate the values from those attributes into the data expandos. For instance:
<div id="test" data-foo='bar' data-test='{"cool": "stuff"}'>Just a div</div>
When selecting that element with jQuery var $test = $('#test'), you can access:
$test.data('foo') // === 'bar'
$test.data('test').cool // === 'stuff'
Read more: http://api.jquery.com/data/
With HTML5, you have the luxury of using data-* attributes - for example:
...
Which jQuery actually has support for - calls to $('a').data() will include the data-* values in it.
For simple things, I use a function like:
function getIdStr(i, sDelim) {
if (typeof i != "string") {
var i = $(i).attr("id");
}
var arr = i.split(sDelim || /_|-/);
if (arr.length > 1) {
return arr[arr.length-1];
} else {
return "";
}
}
// usage
$(function(){
$(".data .action").click(function(){
doSomething(getIdStr(this)); // -> 123
});
});
For something heavier, you might try to attach a data to the topmost container.
i would go with the new Custom Data Attributes HTML5 brings along.
Just use this <a data-action="foo" data-id="bar">...</a>
Also, jQuery already has support to get these data-attributes
You can add a custom property to the input and access it in javascript.
eg
<input type="hidden" name="action" value="abc" yourproperty='<%= Eval("YourDataID") %>'/>

Categories

Resources