Reputation: 53
What I am trying to do is create a gui object that can be used from all the different views. The idea is to add the component as a partial view on the main view by placing the component into a placeholder div.
Here is my model
public class Client
{
public int clientid { get; set; }
public string clientname { get; set; }
}
The java script that I am using to insert the component... Ideally I would prefer to just use the Model data that is passed to this view by a direct call to it, but that was not working which is why I have been troubleshooting with the var model below...
var model = {
clientid: 23,
clientname: "This one"
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "../shared/ClientProgramSelector",
contentType: "application/json"
}).done(function(result) {
$("#clientProgramSelectorPlaceholder").html(result);
});
The controller that is being called is here
[HttpPost]
public PartialViewResult ClientProgramSelector([FromBody] Client passingData )
{
return PartialView("ClientProgramSelector", passingData);
}
and finally, here is the div i am trying to place the component into
<div id="#clientProgramSelectorPlaceholder"></div>
The code is showing no errors, but nothing is rendering on the page. Does anyone see what I am doing wrong? Also, is there a way to just use the passed model instead of having to recreate the data?
Thanks in advance
Upvotes: 4
Views: 2156
Reputation: 218732
Your ajax success handler is trying to set the result to the jQuery element returned by $("#clientProgramSelectorPlaceholder")
. This will return the element with Id value "clientProgramSelectorPlaceholder". But your HTML, you do not have any! What you have is an element with Id "#clientProgramSelectorPlaceholder"
Your div id should be without the #
and it should work as long as your ajax call is returning a 200 OK response.
<div id="clientProgramSelectorPlaceholder"></div>
If you want to render the partial view with the modal data passed to main view, you can call the Html.Partial
method, Assuming your main view is also strongly typed to the same view model(Client
) object
@model Client
<div id="clientProgramSelectorPlaceholder">
@Html.Partial("ClientProgramSelector",Model)
</div>
If you want to pass the original model as the ajax post data, you can use JsonConvert.SerializeObject
method in your javascript code block.
var model = @Html.Raw(JsonConvert.SerializeObject(Model));
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "@Url.Action("ClientProgramSelector","YourControllerNameHere")",
contentType: "application/json"
}).done(function(result) {
$("#clientProgramSelectorPlaceholder").html(result);
});
Upvotes: 3