change div text with ajax not working - c#

What am I doing wrong?
I try to change div text with ajax... but doesn't do anything... I guess the problem is in my controller method..
This my div
<div id="div1">
text to change
</div>
<button>change text</button>
#section scripts{
<script>
$(document).ready(function() {
$("button").click(function () {
$.ajax({
url: "/Home/ChangeText", success: function (result) {
$("#Div1").html(result);
}
});
});
});
</script>
}
This my Controller
public JsonResult ChangeText()
{
var result = "New Text";
return Json(result, JsonRequestBehavior.AllowGet);
}
Note: when is running it's enter to method 'ChangeText' but it doesn't print the result(New Text) on my view

You wrote <div id="div1"> and $("#Div1").html(result);. However div1 not equals Div1, first symbol is big (upper case). JavaScript is sensitive to upper and lower case.
The type attribute specifies the type of button. Always specify the type attribute for the <button> element. Different browsers may use different default types for the <button> element. If you want send data to controller - write type of button type="button" or type="submit".
Attribute values and descriptions:
button - The button is a clickable button
submit - The button is a submit button (submits form-data)
reset - The button is a reset button (resets the form-data to its initial values)
Try this code:
<div id="div1">
text to change
</div>
<button type="button">change text</button>
#section scripts{
<script>
$(document).ready(function() {
$("button").click(function () {
$.ajax({
url: "/Home/ChangeText", success: function (result) {
$("#div1").html(result); // Div1 != div1
}
});
});
});
</script>
}

Related

Refresh div content after OnGet method in Razor Pages

I've got 1 data in view which is assign in OnGet method as a ViewData.
OnGet method:
public void OnGet(string parameter = "default")
{
ViewData["SelectedParam"] = parameter;
}
My View:
#{
var selectedParam= ViewData["SelectedParam"];
}
<h1>Some Page</h1>
<hr />
<div class="row">
<div class="col-3">
<div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
#await Component.InvokeAsync("MyComponent")
</div>
</div>
<div class="col-9">
<div id="mainDiv">
#selectedParam
<hr />
#if (string.IsNullOrEmpty(selectedParam.ToString()))
{
<h5>No param selected</h5>
}
else
{
<h5>#selectedParam selected</h5>
}
</div>
</div>
</div>
My component is sending parameter, View is changing value of ViewData["SelectedParam"] and now I want to refresh the content of a div.
JQuery:
$(document).on('click', 'componentElement', function () {
var parameterResult = "test";
$.ajax({
url: '/Index',
type: 'get',
data: {
parameter: parameterResult
},
success: function () {
<!-- here I need to reload -->
}
});
});
I tried to do location.reload(), but I must refresh only this div, not the whole page, tried also with $('#mainDiv').load(' #mainDiv'), but still nothing
Razor evaluates the View and creates the HTML the client sees. If you examine the source code on Chrome for example, you'll notice all your Razor code was replaced with standard HTML.
If you want to modify the HTML after the page already loaded, you have 2 options. Reload page with new data, so new HTML will be created and the new conditions will be reevaluated, or use JS / JQuery to modify the page on the client side. JQuery won't have access to the ViewData though, this is pure HTML / JS. Since you don't want to reload the page, that's the only way.
Example of JQuery function that removes and adds stuff from the HTML:
$(document).on('click', 'componentElement', function () {
var parameterResult = "test";
$.ajax({
url: '/Home/OnGet/', //assuming controller would be Home
type: 'POST', //if you are sending data, it's a POST
dataType: "Json", //specify the datatype you are sending
data: {
parameter: parameterResult
},
success: function (obj) { //notice I'm expecting an object back here
$( "#mainDiv" ).empty(); //this will clear all the children inside the mainDiv
$( "#mainDiv" ).append("<h5<" + obj + " selected</h5>"); //this will add back the string you get your OnGet
}
});
});
And here is how your OnGet should be to respond to the ajax request:
public JsonResult OnGet(string parameter = "default") //I'll return a Json, so class needs to be JsonResult
{
return Json(parameter);
}

How to handle jquery repeater html in mvc

this is my .cshtml page code,i use jquery repeater is in this code repeater is working fine but i want to add some modification in this repeater but i am stuck here. you can see my code.
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data", #class = "repeater" }))
{
<div data-repeater-list="">
<div data-repeater-item="">
<div class="col-lg-12 col-md-12 col-sm-12">
<input type="file" name="Docfiles" />
</div>
</div>
</div>
<input data-repeater-create type="button" value="Add" />
<button>Save</button>
}
#section Scripts{
<!-- Import repeater js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.js"></script>
<script>
$(document).ready(function () {
$('.repeater').repeater({
// (Optional)
// start with an empty list of repeaters. Set your first (and only)
// "data-repeater-item" with style="display:none;" and pass the
// following configuration flag
initEmpty: true,
// (Optional)
// "show" is called just after an item is added. The item is hidden
// at this point. If a show callback is not given the item will
// have $(this).show() called on it.
show: function () {
$(this).slideDown();
},
// (Optional)
// "hide" is called when a user clicks on a data-repeater-delete
// element. The item is still visible. "hide" is passed a function
// as its first argument which will properly remove the item.
// "hide" allows for a confirmation step, to send a delete request
// to the server, etc. If a hide callback is not given the item
// will be deleted.
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
// (Optional)
// Removes the delete button from the first list item,
// defaults to false.
isFirstItemUndeletable: true
})
});
</script>
}
i want to change html in this formate like this as shown in below screenshot.
Firstly,the name format is set in jquery.repeater.js,if you want to change it,you need to change jquery.repeater.js,here is a demo worked:
1.Add the jquery.repeater.js to your project.
I copy the js to my project like this:
2.Find setIndexes in the jquery and change var newName = groupName + '[' + index + '][' + name + ']' +like this(You can also change it to other format you want):
3.change your script src from cdnjs to your own project:
<script src="~/lib/jquery-repeater/jquery.repeater.js"></script>
4.Result:

Change view using ajax on drop-down list change event

I need to change the view in same page using ajax when the user changes the option of the drop-down list.
Up until now in my view I have the drop down list
<div class="wrapper">
<div>
<label>Get cars per people </label>
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
</div>
<div class="box box-success">
<div class="box-body">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
Then in a script (which I found from another question)
$(document).ready(function () {
$("#ddlChangeID").change(function () {
var strSelected = "";
$("#ddlChangeID:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "/Cars/Index/" + strSelected;
$.post(url, function (data) {
});
});
})
And in the controller I am using ViewBag values to save the drop-down list values and whatever else is needed for the graph which loads in a different script again with ViewBag values. I have managed to pass the selected value (strSelected) but the view does not reload with the new data.
How should I make the ajax event?
Change your script ajax call by calling an action result as follows
$("#ddlChangeID").change(function () {
$.ajax({
url: "/Controller/ActionHtml?id="+$('#ddlChange').val(),
type: "POST",
cache: false,
success: function (result) {
$("#myChart").html(result);
},
error: function () {
$("#myChart").empty();
}
});
});
and in the controller the actionresult will be like the following which returns the html partial view that you need to append
public ActionResult ActionHtml(string id)
{
//Here you can load the data based on the id,pass model to the patial views etc
ViewBag.id = id;
return PartialView("~/Views/Shared/myhtml.cshtml");
}
myhtml.cshtml will be a partial view with the html content as
//content is dummy,change the content as you want
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
</form>
So I changed the
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
To
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #onchange = "ChangeOption()" })
adding also an id to the main div.
And the script to
function ChangeOption() {
var id = $('#ddlChange').val();
$.ajax({
url: '/Cars/Index',
type: "GET",
data: { Id: id },
success: function (data) {
$('#wrapAll').html(data);
}
});
}
It seems to work. Only issue now is that the css breaks.
It pushes the graph and drop-down list to the right breaking
the functionality.

How Rename confirm() buttons in ASP .NET MVC 5 View?

I write in View inside the script tag function.When I click the menu item in view call this function.
I want rename Java script confirm() buttons . How can I do this ? I don't know how write Java script code for this condition .
I follow below code
<script type="text/javascript">
function myFunction() {
var x;
if (confirm("Press a button") == true) {
x = "You pressed Cancel";
} else {
x = "You pressed OK";
}
}
</script>
<li><a><span class="glyphicon glyphicon-log-in" onclick="myFunction()"> </span> Exit</a></li>
ANSWER
You can't control the appearance of confirm() or alert() Javascript dialogs, because they are native, consquently their design is based on the OS/browser.
What you can do:
Own Dialog
Extensions / Plugins
Use a existing dialog js
WAY TO BUILD OWN CLICK ELEMENTS
document.querySelector('#okLI').addEventListener('click', handleClick);
document.querySelector('#cancelLI').addEventListener('click', handleClick);
function handleClick(e){
var target = e.target;
var clickType = target.getAttribute("click-type");
if(clickType > 0)
console.log("CLICKED OK");
if(clickType < 0)
console.log("CLICKED CANCEL");
}
document.querySelector('#ok').addEventListener('click', clickButton);
document.querySelector('#cancel').addEventListener('click', clickButton);
function clickButton(e){
var button = e.target;
var buttonType = button.getAttribute("button-type");
if(buttonType > 0)
console.log("CLICKED OK");
if(buttonType < 0)
console.log("CLICKED CANCEL");
}
<ul>
<li id="okLI" click-type="1">OK</li>
<li id="cancelLI" click-type="-1">CANCEL</li>
</ul>
<button id="ok" button-type="1">OK</button>
<button id="cancel" button-type="-1">CANCEL</button>
You dont need to use buttons, you can add this to every element you want to click.
As you requested, please check jQuery modal dialog for this feature.
you need to include following css and JS in your page.
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Then add following script on your page.
Following script will configure a dialog for you with two buttons, "Delete" and "Cancel" and as you see both have a call back function where you can decide what to do on individual click.
<script type="text/javascript">
$( function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Delete": function() {
// YOUR LOGIC GOES HERE
$( this ).dialog("close");
},
Cancel: function() {
$(this).dialog( "close" );
}
}
});
} );
</script>
and then add following HTML on your page
<div id="dialog-confirm" title="Delete Item?">
<p>Do you want to proceed?</p>
</div>
Finally you just need to call following function, when you want to show dialog.
for example, to trigger it on a button click.. you can make it like following
<button type="button" id="btn_delete">Delete</button>
<script type="text/javascrpt">
$("#btn_delete").click(function(){
$( "#dialog-confirm").dialog( "open" );
});
</script>
You can find more details on following link.
jQuery Dialog
For javascript Confirm
You cannot rename button titles for Javascript Confirm, as it is managed by browser and there is no any library or plugin which can manipulate these components.

asp.net get value from Jquery UI dialog back to first form

I have the below JQuery script
<script type="text/javascript">
$(function() {
$("#no-email-popup").dialog(
{
autoOpen: false,
buttons: {
"ok": function() {
alert($('#new_email').val());
alert(window.top.$("#new_email_label.").val());
// alert(window.top.$("#<%= new_email_label.ClientID %>").val());
$(this).dialog("close");
},
"cancel": function() {
$(this).dialog("close");
}
}
}
);
});
</script>
And and modal asp.net is
<div id="no-email-popup">
<label>Enter Email: </label>
<input type="text" id="new_email" />
</div>
I want to get the value from Pop up back to to asp.net page and assign to label there
<asp:Label ID="new_email_label" runat="server">test top window label</asp:Label>
I found out that I cannot change the value of this label even
Please help how to get value to top asp.net page
Using .val() on a <label/> won't give you the inner html of said label. You would need to use .html() to retrieve it, or .html("something") to set it.
after (or instead) of your alerts, try: $("#new_email_label").val($("#new_email").val());

Categories