I get that the purpose of returning MVC partial views as html was meant to just magically load everything in the viewmodel being passed into my razor-templated view.
However, I only want to selectively load that html model data into my view from my ajax call. I have found zero documentation on parsing this stuff, with the exception being a snippet which supposedly parses the unformatted html into something queryable using jquery:
var modelHTML = $.parseHTML(viewModelData);
I want to go a step further and do:
var elements = $('<div></div>');
elements.html(modelHTML);
var matchingOption = $(elements).find("#selectListID option:first");
alert(matchingOption.val);
but this returns a bunch of jibberish. Is there any way to parse the html returned from a partial view result carrying a viewmodel, rather than returning a json result?
Here's the gist of my controller code:
public ActionResult _MyPartialView(_PartialViewModel pvm)
{
_PartialViewModel _pvm = pvm;
_pvm.shapesList = new List<SelectListItem>();
foreach(var item in context.shapesEntity.Where(x => x.shapeName.HasValue))
{
_pvm.ShapesList.Add(new SelectListItem { Value = item.id, Text = item.name});
}
return PartialView("_myPartialView", _pvm);
}
Note:: I have successfully replaced the HTML in my partial view with the html in this div. So that works and is the way I am seeing people use partial view html results. But I want to query this with jquery and use pieces of the result as I please.
Try this out, I think I see where the problem is.
First of all on this line.
You don't need to use parseHTML (I doubt it'd hurt), because the return value of your action is already the HTML and you can just use that when setting the HTML of your div.
All of that above looks fine, should do exactly what you want (assuming the HTML in your action has an ID called selectListID and it has an option in it).
I think the below line is where you have a mistake.
val is a function, so you're getting the function definition returned. What you want is something like this.
You could of course use alert instead, I prefer console.log, you could also use
console.log(matchingOption)
to just spit out the object to your console.