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);
}
Related
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.
My website consumes an API that I have written. Currently I have written a page that consumes a GET, and a page that consumes a POST. I am having a lot of trouble with PUT however.
I currently have two functions with the same name, but different arguments. I have ChangeOneEmu(), and ChangeOneEmu(EmuItem model), the second being the "put" method.
I learned through a previous question of mine that I cannot get HTTP forms, or even the tag, to send things via a PUT method since HTTP doesn't support PUT. So I've been attempting to use AJAX to send it via PUT and it also doesn't appear to be working.
Essentially, what is happening as of right now is that my function with no arguments calls the view, which loads the View correctly-I can input data just fine. When I press the "submit" button however, it doesn't go to my PUT method (the action that takes in the model argument). It just returns to the no argument action.
Here is the code I have implemented in my controller:
public IActionResult ChangeOneEmu()
{
return View(new EmuItem());
}
[HttpPut]
async public Task<IActionResult> ChangeOneEmuNew(EmuItem model)
{
var response = await client.PutAsJsonAsync(model.SearchName, model);
return RedirectToAction("Index");
}
And here is the code I have implemented in my View:
#model HelloEmuWebsite.Models.EmuItem
<script>
$(document).ready(function () {
$("SubmitMe").click(function () {
$.ajax({
url: '#Url.Action("ChangeOneEmuNew", "Home")',
type: 'PUT',
data: $('changeemuform').serialise(),
//dataType: 'json',
success: function (result) {
alert(result);
}
});
return false;
});
});
</script>
<form method="put" id="SubmitMe">
<div>
#Html.LabelFor(x => x.SearchName)
#Html.TextBoxFor(x => x.SearchName)
</div>
<div>
#Html.LabelFor(x => x.Name)
#Html.TextBoxFor(x => x.Name)
</div>
<div>
#Html.LabelFor(x => x.Age)
#Html.TextBoxFor(x => x.Age)
</div>
<div>
#Html.LabelFor(x => x.Weight)
#Html.TextBoxFor(x => x.Weight)
</div>
<input type="submit" value="OK" id="SubmitMe" ; />
</form>
And just in case, here is what my actual API implementation is:
[HttpPut("{id}")]
public ActionResult<List<Models.EmuItem>> Put(string id, [FromBody] Models.EmuItem ChangedEmu)
{
if (ModelState.IsValid)
{
return MyEmus.ChangeEmu(id, ChangedEmu);
}
return BadRequest(ModelState);
}
I would love any help at all. I'm not sure if I'm fundamentally misunderstanding how the ASP.NET CORE MVC pattern operates, or how forms operate, or how AJAX operates, or all three or none. Thank you.
Make the following changes in your view :
add id="changeemuform " in <form>
<form method="put" id="changeemuform">
put your jQuery in #section Scripts {} and use the correct format of $("#id")
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#SubmitMe").click(function () {
$.ajax({
url: '#Url.Action("ChangeOneEmuNew", "Home")',
type: 'PUT',
data: $('#changeemuform').serialize(),
//dataType: 'json',
success: function (result) {
alert(result);
}
});
return false;
});
});
</script>
}
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>
}
When I select Date in DateTimePicker, it's invoking public ActionResult Index(DateTime? test). It returns some items into the view, but those items do not appear on Index. It seems that this does not work, and I'm unsure why:
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<Table> temp = new List<Table>();
return View(temp);
}
[HttpPost]
public ActionResult Index(DateTime? test)
{
masterEntities m = new masterEntities();
List<Table> temp = m.Table.Where(key => key.Date == test).Select(key => key).ToList();
return View(temp);
}
}
Index.cshtml:
#model IEnumerable<DatePicker.Models.Table>
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$('#datetimepicker1').datetimepicker({ useCurrent: false });
$('#datetimepicker1').on("dp.hide", function (e) {
//var temp = $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm')
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
});
</script>
</div>
</div>
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
First you send an empty list to the view:
List<Table> temp = new List<Table>();
return View(temp);
So the loop doesn't show anything because, well, there's nothing to show. It's an empty list.
Then you make an AJAX request to get items:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
But you don't do anything with those items. You basically ignore the response from the AJAX request.
So... The data doesn't display because you haven't written any code to display the data. The AJAX request should have some sort of callback function to do something with the returned response:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
success: function (data) {
// do something with the response here
}
});
What you do with the response is up to you. Is it JSON? HTML? Based on the server-side code, it looks like it's HTML. So you can maybe put it into an element on the page. Something like this, perhaps:
$('#someElement').html(data);
That's just one example, and would of course require an element of some sort that you can identify to hold the response. You could do a lot of other things with the response.
One thing to note, however, is that your response appears to be an entire page. It includes script tags, link tags for CSS, and all sorts of markup that you otherwise already have on the client. So putting the entire page into an element isn't going to work right.
You might want to return just a partial view for this AJAX response. Or, otherwise, instead of using AJAX at all just navigate to the action to get that entire page.
I am loading two partial views in my application. On click in the menu, calls the controller twice from div.load() in ajax call. How to avoid the controller calling twice.
Jquery Ajax call :
$(document).ready(function () {
$('.common').click(function () {
var pageid = this.id;
LoadPartialView(pageid);
});
});
function LoadPartialView(pageid) {
alert('pass');
var urls = '/WPindex/' + pageid + '/'
$.ajax({
url: urls,
type: 'GET',
contentType: 'application/html',
success: function (result) {
$('#divDefault').hide();
$('#divDynamic').load('/WPindex/' + pageid);
}
});
}
View
<body>
<div>
<ul>
<li><a id="MyAccount" class="common"><strong>Account Dashboard</strong></a></li>
<li><a id="AccountDetails" class="common">Account Information</a></li>
<li><a id="AddressBook" class="common">Address Book</a></li>
</ul>
</div>
<div id="divDefault" class="order">
</div>
<div id="divDynamic" class="order">
</div>
</body>
Controller
public ActionResult AccountDetails()
{
return PartialView();
}
Here on click on the AccountDetails anchor tag, the partial view is loaded. But the controller is called twice. What is the mistake in my code. ?
Any suggestions for bringing the partial view ??
Well,
$.ajax({
...
part makes the first call to the controller, and
success: function (result) {
...
$('#divDynamic').load(...
makes the second one. If your task is just to load data in the div, you can get by with just one line:
$('#divDynamic').load('/WPindex/' + pageid);