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);
Related
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);
}
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>
}
I want to click "2" Ajax will call ActionResult and put new question up but not rerun page
i have been trying two day but it haven't worked
People help me, please
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return View(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Json",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
In HTML:
<li>
1
</li>
enter image description here
Thanks for reading
I changed but it dont work!!
I learned it myself so it was hard to get started
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return PartialView(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Html",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#baitetstiq').html(a);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
Full HTML:
<div class="col-md-9" style="border-top-style:double;
border-top-color:aquamarine;
border-top-width:5px; margin-left:-15px">
<p style="text-align:center">
<b>Thời Gian Còn Lại Là:xxx</b>
</p>
<div id="baitestiq"></div>
#foreach(var item in Model)
{
<div class="baitest">
<div class="ques">
<img src="~/Hinh_Cauhoi/#item.Cauhoi" />
</div>
<div class="anw">
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn1" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn2" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn3" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn4" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn5" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn6" />
</div>
</div>
<div class="numbertest">
<ul>
<li>
1
</li>
</ul>
</div>
1st you need to return a partial view.
2nd you need to make a get ajax request and not a post
3rd you need to test first the result of #Url.Action("BaiTestIQ","TestIQ"), translate this to a URL, directly to make sure it returns the expected results without the ajax call to avoid getting into sideways with routing etc. see this for example
See a working example here
Update:
I see it now, you changed dataType: "Html"
You need to change several things:
1. The method is not changing any state so it should not be declared as a post method. You need to remove [HttpPost] attribute.
You need to be aware of ajax parameters contentType and dataType. From the documentation: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8'). This specifies what type of data you're sending to the server. And dataType (default: Intelligent Guess (XML, json, script, or HTML)) specifies what jQuery should expect to be returned. In your case, it should be 'json' because you are using the result return from a LINQ query.
So the method might look like:
public JsonResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return Json(cauhoi.ToList(), JsonRequestBehavior.AllowGet);
}
3. Moving to the ajax call:
<script>
function loadcauhoi(num) {
$.ajax({
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
type: "GET",
cache: false,
dataType: "json",
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
**But I'd like to suggest another approach using a ViewModel with a partial view because serializing JSON data can sometimes get you errors. A quick tutorial
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.