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.
Related
I'm trying to return the text from another page on my domain into an input text box. I can return the text inside a div (DivThisPage) but can't seem to get the text from the div I've loaded in to the text input field (txtValue).
function getValue() {
$("#DivThisPage").load("http://another-page-on-my-site #DivTheOtherPage"); //This is working and I see "test" on this page.
var myVal = $('#DivThisPage').val(); //I've tried both DivThisPage and DivTheOtherPage but get nothing
$("#txtValue").val(myVal);
}
Here is the HTML on this page:
<button onclick="getValue()">Get Value</button>
<div id="DivThisPage"></div>
<input type="text" id="txtValue" name="txtValue" />
The html from another page on my site:
<div id="DivTheOtherPage">test</div>
However, when I inspect the elements on the page after executing I see:
<div id="DivThisPage">
<div id="DivTheOtherPage">test</div>
</div>
But when I debug the script myVal is always null.
You have two issues here. Firstly, div elements do not have a value attribute so the val() method doesn't work for them. Assuming from the context of the question you want to get the text within the element, use html() or text().
Secondly, the AJAX call used by load() under the hood is asynchronous. This means that you will need to use the callback argument in order to read the data from the DOM after it has been updated.
<button>Get Value</button>
<div id="DivThisPage"></div>
<input type="text" id="txtValue" name="txtValue" />
jQuery(function($) {
$('button').on('click', function() {
$("#DivThisPage").load("/relative-path #DivTheOtherPage", function() {
var myVal = $('#DivTheOtherPage').text();
$("#txtValue").val(myVal);
});
});
});
Also note that use of an unobtrusive event handler here. Inline event attribute are now considered bad practice (as they tie the HTML and JS logic too tightly) and should be avoided where possible.
In addition, if you're making a call to a location on your own site, use a relative link.
Uses this:
function getValue() {
$("#DivThisPage").load("http://another-page-on-my-site #DivTheOtherPage", function(response, status, xhr){
var myVal = $('#DivThisPage').val();
$("#txtValue").val(myVal);
});
}
i have one jsp page(addStep1.jsp) where i have lot of input fields and drop downs to get values from user.
among all the dropdowns i want to get value from one of the drop down whose id is svoAffectedSoftware.
<select id="svoAffectedSoftware" name="svoAffectedSoftware" class="form-control" >
Now, on the same page i want to include other jsp file for which i have uses below code (i have uses two approach to solve this but in both the cases i am not getting the desire output. the problem in first approach is i am not getting any error but my page doesn't comes up not even my addStep1.jsp where i have included this code and in the second approach it saying:: The method $(String) is undefined for the type
__2F_ssappmgr_2F_webapps_2F_sam_2F_apps_2F_itapp_2F_ticket_2F_addStep1_2E_jsp. )
approach 1
<%# include file="ticketResolutionChatBot.jsp?svoAffectedSoftware="svoAffectedSoftware %>
or
approach 2
<jsp:include page="ticketResolutionChatBot.jsp" >
<jsp:param name="svoAffectedSoftware" value="<%= $("#svoTicketState").val() %>"/>
</jsp:include>
can anyone tell me how do i pass parameter in the correct way also how to achieve this?
I would like to suggest you to use javascript for this purpose. With jQuery it is very easy to achieve your goal.
Include jQuery library in your jsp page
Example is here https://www.w3schools.com/jquery/jquery_get_started.asp
And here: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_lib_microsoft
Don't forget to use all your jquery code inside
$(document).ready(function(){
// your code for the page
});
use my example for you from fiddle
https://jsfiddle.net/u0frjksd/3/
This function subscribes to your select value and loads content page, based on the selection:
$(".form-control").on('change', function() {
var value = $(this).val();
$('.content').load(value);
});
Instead of first value you can provide your own value, I mean your href(in value) to the jsp page you want to include.
Your jsp page will be loaded to the div .
i have uses change() and ajax function here.
$('#svoAffectedSoftware').change(function() {
var form_data = {
svoAffectedSoftware: $("#svoAffectedSoftware").val()
};
$.ajax({
type: "GET",
cache: false,
url: "getNewPage.jsp",
data: form_data,
success: function(data){
$("#contentDiv").html(data);
}
});
});
where, url: "getNewPage.jsp"--> redirecting page,
var form_data = {svoAffectedSoftware: $("#svoAffectedSoftware").val()}; --> takes value for the new page which i was asking through parameter,
success: function(data){$("#messageDiv").html(data);} --> include the content of the resultant page into original page (addStep1.jsp) in the specified div.
I'm trying to make a dynamic form with AngularJS and JavaScript. The objective is to add how many inputs the user need and transform all those inputs in AngularJS variables that print it on body. So I got that code:
$(function(){
var number = 1;
$('a.add').click(function(e){
e.preventDefault();
$('#this_div_contains_settings').append('<input type="text" name="example'+number+'" ng-model="example'+number+'" placeholder="Anything">');
number++;
});
$('#this_div_contains_settings').on('click','a.design_button', function(e){
e.preventDefault();
$(this).parent().remove();
});
});
This function add a INPUT on my DIV with the different ng-model every time it run.
The problem is, it just work's if the {{example1}} is already on my BODY, if I add it later with another function, it just doesn't work.
I'm new with AngularJS, so I didn't understand if I need to "refresh" the AngularJS everytime I add new variable or something like that.
Any help will be appreciated :)
Using jQuery is the wrong way to solve this problem. Instead, create an array inside of your controller that will hold the models for all of these inputs.
Depending on how you define/create your controllers, $scope may be replaced with this
$scope.examples = [];
Next, create a function that will add a new example to the array:
$scope.addExample = function () {
$scope.examples.push("");
}
Now, in your template, create the inputs using an ng-repeat:
<div id="this_div_contains_settings">
<input ng-repeat="example in examples" type="text" name="example" ng-model="example" placeholder="Anything">
</div>
and have your "add" button call your addExample function on click:
<a class="add" ng-click="addExample()">Add Example</a>
Finally, remove all of the code that was included in your question.
And for your .design_button that removes all the examples, that's easy too:
<a class="design_button" ng-click="examples = []">remove all examples!</a>
by that same concept, you could even remove the need for the addExample function, however i tend to keep logic in the controller (well, actually in the services, but that's another topic) anyway rather than putting it in the template.
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
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") %>'/>