Update the data in View with AJAX not working - ajax

I have diffrent <a> tags that normally pass a parameter to an action using asp-route="". Now i want to use AJAX t do this. each tag is supposed to pass an ID that comes from the model chats when the page loads up. (asp-route-ChatID="#Model.ID").
How can I achieve this in AJAX and pass that parameter? I tried using Data-ajax-update and Data-ajax-url but these option arent even available in Intellisense. Here is the method that i want to call
public IActionResult Chat(string ChatID)
{
Chats userchats=new Chats(); // a class that holds chats
//selecting data from the database......
return View(userchats);//returns view with the model
}
here is the <a> tag that gets clicked and it needs to pass a specific ID that comes from the model
<a > View Chat </a>
here is the <div> that needs to be updated depending on what <a> is clicked
<div id="UpdateThis"> <!--show data that comes from the method ajax calls--> </div>
How can I implement ajax here with tag helpers or any other way?

Use PartialView instead of view if you want to update div.
public IActionResult Chat(string ChatID)
{
Chats userchats=new Chats(); // a class that holds chats
//selecting data from the database......
return PartialView(userchats);//returns view with the model
}
View
<a id="btnView" data-id="1">View Chat</a>
<div id="UpdateThis"></div>
<script>
$("#btnView").click(function () {
$.post('#Url.Action("Chat")', { ChatID: $(this).data("id") }).done(function (e) {
$("#UpdateThis").html(e);
})
});
</script>

Related

Call Controller Method Which Return View With Ajax Call From Asp.net MVC View Page

i'm using .Net core 2.1 application, inside for loop how can i trigger controller view page without returning to ajax response,
see following code
this is my razor view
#foreach (var item in Model.CategoryList)
{
<div class="col-sm-6 col-md-4 mb-4 mb-lg-0 col-lg-2" onclick="SelectCategory(#item.CategoryId)">
<a href="#" class="popular-category h-100">
<span class="icon"><span class="#item.Icon"></span></span>
<span class="caption mb-2 d-block">#item.CategoryName</span>
<span class="number">32,891</span>
</a>
</div>
}
<script>
function SelectCategory(id) {
$.ajax({
type: 'POST',
url: '#Url.Action("ProductsList","Home")',
dataType: 'json',
data: { parentId: id }
});
}
</script>
public ActionResult ProductsList(int parentId)
{
List<PilCategory> all = new List<PilCategory>();
if(parentId > 0)
all = _context.PilCategory.Where(x=>x.ParentId == parentId).OrderBy(a => a.ParentId).ToList();
else
all = _context.PilCategory.OrderBy(a => a.ParentId).ToList();
return View(all);
}
pls someone help me, thaks for advance
how can i trigger controller view page without returning to ajax response
As far as I know, we couldn't trigger controller view page without returning to ajax response. Since the ajax will send the request to the controller view and the controller view will return the view as html response back to the ajax.
If we don't handle the response, that means current page will not change.
If you just want to pass the parentId to the ProductsList method, I suggest you could try to use window.location, this will make this page redirect to the ProductsList view which achieve refresh the whole page.
Notice: If we using ajax to call ProductsList, the whole page will not refresh. If we using window.location, it will redirect to another page or refresh the whole page.
More details about how to achieve this, you could refer to below codes:
#section Scripts{
<script>
function SelectCategory(id) {
location.href = "/Home/ProductsList?parentId=" + id;
}
</script>
}
If you want to use ajax to achieve this, I suggest you could try to handle the response by using ajax success method. Normally, we will return the partial view in controller method and then we could add it into the html page by using jquery without refreshing the page.
More details about how to achieve this, you could refer to this answer.

Load partial view depending on dropdown selection in MVC3

Im trying to create a from using asp.net mvc3.
I have a dropdownlist with some options.
What i want is different partial views to be injected into the page, depending on the selection in the dropdown list.
But. i dont want this to rely on a submit action. It should function so that, the partial view is loaded as soon as you select from the select list.
I have this code:
#using (Ajax.BeginForm("Create_AddEntity", new AjaxOptions {
UpdateTargetId = "entity_attributes",
InsertionMode = InsertionMode.Replace
}
))
{
<div class="editor-label">
#Html.Label("Type")
</div>
<div class="editor-field">
#Html.DropDownList("EntityTypeList", (SelectList)ViewData["Types"])
</div>
<div id="entity_attributes"></div>
<p>
<input type="submit" value="Create" />
</p>
}
But I can't figure out how to trigger this partial view load when the dropdown list selection changes.
This point is that the form is different for the different "entity types". so there will be loaded a different partial view, depending on the dropdown selection.
Anyone got any pointers?
Let's say following is your view that you want to insert your partial.
<html>
<head><head>
<body>
<!-- Some stuff here. Dropdown and so on-->
....
<!-- Place where you will insert your partial -->
<div id="partialPlaceHolder" style="display:none;"> </div>
</body>
</html>
On the change event of your dropdownlist, get partial via jquery ajax call and load it to place holder.
/* This is change event for your dropdownlist */
$('#myDropDown').change( function() {
/* Get the selected value of dropdownlist */
var selectedID = $(this).val();
/* Request the partial view with .get request. */
$.get('/Controller/MyAction/' + selectedID , function(data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
And in your controller action which is /Controller/MyActionin above jquery, return your partial view.
//
// GET: /Controller/MyAction/{id}
public ActionResult MyAction(int id)
{
var partialViewModel = new PartialViewModel();
// TODO: Populate the model (viewmodel) here using the id
return PartialView("_MyPartial", partialViewModel );
}
add the following code to the header of the project (layout).
Add "combobox" to any combo box (select box) which you want to trigger the form that is surrounding it.
$(document).ready(function () {
$('.formcombo').change(function () {
/* submit the parent form */
$(this).parents("form").submit();
});
});

Binding Model data to Knockout ViewModel?

Is it possible to bind data from your model to a knockout viewmodel. Heres an example:
public ActionResult Edit(int id)
{
Product product = _db.Products.FirstOrDefault(x=>x.ItemId == id);
return View(product);
}
Then in the View I would traditionally do something like so:
#model myApp.Models.Product
#using(Html.BeginForm())
{
#Html.EditorFor(x=>x.ItemName)
#Html.ValidationMessageFor(x=>x.ItemName)
<input type="submit" value="Update" />
}
But with Knockout I would create a EditProductViewModel from where I would do something like:
var EditProductViewModel = {
ItemName = ko.observable('')
};
EditProductViewModel.Edit = function() {
$.ajax({
url: "Home/Edit",
data: ko.ToJson(this),
success: function() {
// do something
}
});
};
$(function() {
ko.applyBindings(EditProductViewModel);
});
And instead of using the Html Helpers I would do something like so in my view:
<form data-bind="submit: Edit">
<input type="text" data-bind="value: ItemName" />
<input type="submit" value="Update" />
</form>
So how can I populate this with the data returned from my controller?
I don't have a any experience with knockout but it would seem to me that you would no longer want to return a view from your controller how about
return JSON(product)
that way you would get a json element of the product on your javascript success function you would need to collected the json element
$.ajax({
url: "Home/Edit",
data: ko.ToJson(this),
success: function(data) {
// map to knockout view model
}
});
and then from here you would call the map bindings.
When using knockout you have two ways to do this.
1. Load your textboxes, etc in one view. Upon loading that view for the first time convert your model to JSON upon in initial load to use by knockout.
ALL additional calls to/from go via JSON.
You can use in your View:
#Html.Raw(Json.Encode(yourModel))
Load your textboxes in your view (ie they are part of your vieW)
Trigger off on document.ready() your ajax calls to get your data from your controller, convert to JSON ie return Json(yourModel, JsonRequestBehavior.AllowGet) and bind those results roughly as you are already doing above
Note - the downside with this approach is with validation. If you have all client side validation, then this is OK as the attributes for data-* will have been written out by MVC to your textboxes, etc. If you have any server side validation, there is no 'smooth' built in integration here with knockout.
There's a decent article here:
http://www.codeproject.com/Articles/305308/MVC-Techniques-with-JQuery-JSON-Knockout-and-Cshar
but still lacks on server side validation mention.
You could serialize data to your page and then initialize knockout viewmodel with values from server.
ItemName = ko.observable(serializedModel.ItemName);

View with multiple partial views posting back

I'm new to MVC (MVC3) so not sure about the best way to implement this.
I want to create a single "main" view (not strongly-typed). This "main" view will contain multiple strongly-typed partial views that each contain a form. Each partial view will therefore post back to their own POST action that does whatever. The problem I see is that when a partial view posts back, it needs to only update the partial view itself and not affect the other partial views on the page.
When I postback from a partial view now, it just returns the partial view alone back, rather than the entire "main" page.
How can this functionality be achieved in MVC3? (from a high-level perspective)
Thanks
You can post data by AJAX.
In my example I use jQuery:
<div id="first-form" class="form-container">
#Html.Partial("FirstPartial")
</div>
<div id="second-form" class="form-container">
#Html.Partial("SecondPartial")
</div>
// and here go rest forms
Your partial view may be following:
#model YourModelClass
#using (Html.BeginForm())
{
// some fields go there
}
<input type="button" value="Save Form Data" class="save-button"/>
Js would be following:
$("input.save-button").on("click", function () {
var button = $(this);
var container = button.closest("div.form-container");
var url = container.find("form").attr("action");
container.busy($.post(url, function (response) {
container.html(response);
}));
return false;
});

How to TryUpdateModel from outside of Controller in MVC3

My app has modules that can be turned on and off and these modules are contributing to a view via Html.Partial calls. When the page posts back to the controller I want to have the modules take care of their individual models using something like TryUpdateModel that the controller has. Problem is that TryUpdateModel is a protected method and not accessible from outside the controller.
How can I do something like Controller.TryUpdateModel from a class outside of the controller?
If I am reading this right, it sounds like you are wanting a partial view to update itself.
I have done something similar with some jQuery, by calling an action and returning a partial view inside of a partial view. Inception?
Simple Example. - really simple
_partialViewStart.cshtml
<div id="partialFillerResult">
</div>
<script type="text/javascript">
$(document).ready(function() {
loadPartialViewFiller();
});
function loadLatestTribes() {
$("#partialFillerResult").load("#Url.Action("PartialViewFiller", "Home")").fadeIn("slow");
setTimeout(loadPartialViewFiller, 5000);
}
</script>
HomeController.cs
public ActionResult PartialViewFiller()
{
var yourModel = new ExpandoObject();
if (yourModel == null) return PartialView("_empty");
return PartialView("_partialViewFiller", yourModel);
}
_partialViewFiller.cshtml
#model dynamic
<div class="objectWrapper">
<p>
#Model.Name
</p>
</div>

Resources