Passing the selected object id to the #HTML.Action parameter - c#

Once again, I added an post, this time corrected, because the previous one was difficult to understand
I have a page where directories are shown something like a network drive
Here is the main Action to render view with catalogs:
public ActionResult Index(int? id)
{
return View(_context.NodeEntities.Where(x=>x.ParentId == id));
}
This action renders the view:
#model IEnumerable<Tree.Models.Node>
#{
ViewBag.Title = "Home Page";
}
<div class="container">
<div class="row">
#foreach (var node in Model)
{
<div class="col-md-3 one-node mx-3" id="#node.Id" onClick="Select(this.id)">
<img src="https://img.icons8.com/color/144/000000/folder-invoices.png">
#Html.ActionLink(node.Name, "Index", "Home", new { node.Id }, new { #style = "display:block;" })
</div>
}
</div>
<!-- Button trigger modal -->
<button id="change_name" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Change name
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Change name:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="modalBodyId" class="modal-body">
#Html.Action("EditName", "Home", new { id = 1 })
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<script>
var div;
function Select(clicked_id) {
if (div != null) {
div.style.removeProperty('background-color');
}
div = document.getElementById(clicked_id);
div.style.backgroundColor = "lightgreen";
}
</script>
I would like to do something such that when a user clicks on a given folder, he is shown the option rename. After clicking change name, a pop-up appears in which the user can change the name of the selected folder. And what I wrote about it is done, but not completely. For me, it works so that when you click just change the name, a pop-up window appears and #HtmlAction is launched in the "modal-body":
public PartialViewResult EditName(int id)
{
Node node = _context.NodeEntities.FirstOrDefault(x => x.Id == id);
return PartialView("_EditName", node);
}
Here is the PartialView:
#model Tree.Models.Node
#using (Html.BeginForm("ZmienNazwe", "Home"))
{
<div class="form-group">
#Html.TextBoxFor(m => m.Name)
</div>
}
It works, but I passed in #Html.Action parameter "id = 3" and I would like to put there the id of the selected folder
Screen showing the problem

You cannot use Html.Action for this. It will execute ounce when the page loads, but you cannot update the route values dynamically client-side and have Html.Action execute again to fetch the new partial view. You would have to reload the whole page, and pass Html.Action the new value.
To do what you want you first have to add a custom click event to your "Change name" button that fetches the correct partial view, then displays the modal.
First remove data-toggle="modal" data-target="#exampleModalCenter" from you button so that Bootstrap doesn't wire up a click event to the button since we are creating our own.
<button id="change_name" type="button" class="btn btn-primary">
Change name
</button>
Next write some javascript to wire up your own click event to this button:
$('#change_name').on('click', function (e) {
e.preventDefault();
var id = 1; // TODO: Get id of selected node
$.get('/path/to/EditName/' + id, function (html) {
$('#exampleModalCenter .modal-body').html(html);
$('#exampleModalCenter').modal('show');
});
});
UPDATE
Most times I like to have my url generation on the server-side instead of having a string somewhere in javascript file or view.
To do this I will geneate my url with #Url.Action on the button.
On a button you can do this:
<button id="change_name" type="button" class="btn btn-primary" data-base-url="#Url.Action("EditName", "Controller")">
Change name
</button>
And javascript update:
var url = $(this).data('base-url');
$.get(url + '/' + id, function (html) {
Or simply use an <a> tag (instead of a button) and href attribute:
<a id="change_name" href="#Url.Action("EditName", "Controller")" class="btn btn-primary">
Change name
</a>
And javascript updates:
$.get(this.href+ '/' + id, function (html) {

Related

Display a modal popup div from controller

Can please someone help me here?! Thank you!
I have a view that displays a list of products along with an "Add Product" button for each. I am calling the CreateNewProduct method for each "Add Product" click to find the status of the product. Depending on the status, either I need to stay on the same view or I need to call a modal popup. I am able to do this by creating a modal popup in a different view. But I want to call the modal popup div (also pass the modal) from the same view where it displays a list of products. Is this possible?
public ActionResult CreateNewProduct(int productId)
{
var sharedProduct = _productTemplateService.GetSharedProducts(productId);
var _finalSharedProducts = (sharedProduct.Any(t => t.productId != productId));
if (_finalSharedProducts)
{
var sharedProdctTemplate = _productTemplateService.GetSharedProduct(productId);
return View("ModalView", new SharedModel
{
SharedProduct = sharedProdctTemplate
});
}
else
{
_productTemplateService.CreateNewProduct(productId);
return RedirectToAction("Details", "ProductTemplate");
}
}
Model View Code
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Shared Product</h4>
</div>
<div class="modal-body">
<div class="flex-row">
<div class="col-6">
<div class="d-flex flex-row">
<div class="p-2">Product ID</div>
<div class="p-2">Product Types</div>
<div class="p-2">Status</div>
</div>
#foreach (var productTemplate in Model.SharedProduct )
{
<div class="d-flex flex-row">
<div class="p-2">#productTemplate.ProductId</div>
<div class="p-2">#productTemplate.ProductType</div>
<div class="p-2">#productTemplate.StatusCode</div>
</div>
}
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List", "Index")
</p>
<script type="text/javascript">
$(document).ready(function () {
$('#myModal').modal('show');
});
</script>
UPDATE:
I made it working. This is what I did. At the end, I have mentioned issues I am facing.
Link, modal and script in my main view - Detail View (called from ProductTemplate Controller)
<td>Add New Product</td>
<div class="modal fade" id="mymodel" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Shared Products</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="mymodelbody">
</div>
</div>
</div>
<script>
var loadModal = function (productId, customerId) {
$.ajax({
type: 'GET',
url: '/NewProductTemplate/CreateNewProduct',
cache: false,
data: {
productId: productId,
customerId: customerId
},
dataType: 'html',
success: function (data) {;
$("#mymodelbody").html(data);
$("#mymodel").modal("show");
}
});
}
</script>
NewProductTemplateController Code
public ActionResult CreateNewProduct(Guid productId, Guid customerId)
{
var sharedProduct = _productTemplateService.GetSharedProducts(productId);
var _finalSharedProducts = (sharedProduct.Any(t => t.productId != productId));
if (_finalSharedProducts)
{
var sharedProdctTemplate = _productTemplateService.GetSharedProduct(productId);
return PartialView("_shared", new SharedModel
{
SharedProduct = sharedProdctTemplate
});
}
else
{
_productTemplateService.CreateNewProduct(productId);
return RedirectToAction("Details", "ProductTemplate");
}
}
Partial view _shared.view code
#model SharedModel
#using (Html.BeginForm("ShareProduct", "NewProductTemplate", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="flex-row">
<div class="col-6">
<div class="d-flex flex-row">
<div class="p-2">Product ID</div>
<div class="p-2">Product Types</div>
<div class="p-2">Status</div>
</div>
#for (var i = 0; i < Model.SharedProducts.Count(); i++)
{
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).ProductId)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).CustomerId)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).ProductType)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).StatusCode)
#Html.HiddenFor(model => model.SharedProducts.ElementAt(i).IsShared)
<div class="d-flex flex-row">
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).ProductId)</div>
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).ProductType)</div>
<div class="p-2">#Html.DisplayFor(model => model.SharedProducts.ElementAt(i).StatusCode)</div>
#if (Model.SharedProducts.ElementAt(i).StatusCode == VersionStatus.PUBLISHED)
{
<div class="p-2">#Html.EditorFor(m => m.SharedProducts.ElementAt(i).IsShared)</div>
}
</div>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-sm btn-primary" />
<button type="button" class="btn btn-sm btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
PROBLEM:
1) When I save submit button in modal pop-up (partial view), it calls ShareProduct method from NewProductTemplate controller. For some reason, model SharedModel's SharedProducts property is null when it gets to controller code. Can you please help me here why it gets null?
public ActionResult ShareProduct (SharedModel shareModel)
{
//Access ShareProducts from shareModel
return RedirectToAction("Details", "ProductTemplate");
}
PROBLEM:
2) I want to load popup only if the product is shared, otherwise I just want to redirect to Detail view as mentioned in NewProductTemplate controller's CreateNewProduct method. Problem is that it loads Detail view also in popup if product is not shared since that's what my script is doing. Is there any way that I can check data in Success function before showing modal popup? If data/html contains Shared text, I would like to load the normal Detail view. I am just assuming. I tried to do so but with no success.
Detail method in ProductTemplate Controller
public ActionResult Details()
{
var productTemplate = _productTemplateService.GetAllProducts(User);
return View(new DetailsModel
{
ProductTemplate = productTemplate,
});
}
(This is for Bootstrap 3.3.7 Hopefully it's relevant for the version you're on)
I handle this by popping open the modal on the client side from my main view. The link that pops the modal contains the URL to the controller method that will render the actual contents (list of products, in your case). This controller method should return a partial view.
Modal in my main view:
<div class="modal fade name-of-my-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content"></div>
</div>
</div>
Link in my main view:
<a class="btn btn-default btn-xs" data-toggle="modal" data-target=".name-of-my-modal" role="button" href="/SomeController/SomeMethodThatReturnsPartialView/234">Show Modal</a>
My controller method for the partial view:
public ActionResult SomeMethodThatReturnsPartialView(int id)
{
var model = GetProducts();
return PartialView("_IndexPartial", model);
}
My partial view that will populate the actual modal contents:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Title goes here</h4>
</div>
<form class="form-horizontal" id="SomeId" name="SomeName" role="form">
<div class="modal-body">
<div>Product 1</div>
<div>Product 2</div>
<div>Product 3</div>
<div>Product 4</div>
</div>
</form>
Also, if the contents of the modal change frequently, or are variable based upon the ID you pass to the partial controller method, then you'll want to clear the modal contents when closing it. From your main view:
$(document).on('hidden.bs.modal', '.modal', function (e) {
// Handles the event thrown when a modal is hidden
$(this).removeData('bs.modal');
$(this).find(".modal-content").empty();
});
Let me know if this helps, and whether anything needs to be clarified.
Problem 2 you could return a JSON result and put the HTML in a string as shown here:
https://www.codemag.com/article/1312081/Rendering-ASP.NET-MVC-Razor-Views-to-String
you could also set a boolean on the returned JSON for whether to redirect.
If it is a redirect do that in Javascript on the success using
window.location

Modal from Ajax loaded partial view is not showing after clicking button one time

I am trying to create a partial view that will appear in a modal when a button gets pressed. If there is another approach that works better for this, I am open for it -- I had the modal working great until I added the List to the main view. If there is a way to return back a list and form post a single entity that might work for my scenario. Right now the code I have works to an extent, however you need to push the Add Service button twice in order for the modal to show up and when it does the only way to get rid of it is to submit, both the X in the top as well as the close button don't work.
main view
#model List<ServicesPosting>
<div>
<button id="addService" onclick="OpenModal()">Add Service</button>
</div>
<div id="AddServiceForm"></div>
<script type="text/javascript">
function OpenModal() {
var url = '#Url.Action("AddServiceModal", "Services")';
$('#AddServiceForm').load(url);
$('#serviceModal').modal();
}
</script>
controller
public class ServicesController : Controller
{
// GET: Services
public ActionResult Index()
{
List<ServicesPosting> postings = DataAccess.GetAllPostings();
return View(postings);
}
[HttpGet]
public ActionResult AddServiceModal()
{
return PartialView("~/Views/Services/AddNewService.cshtml");
}
}
partial view
#model ServicesPosting
<!-- Modal -->
<div class="modal fade" id="serviceModal" tabindex="-1" role="dialog" aria-labelledby="serviceModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="serviceModalLabel">Add New Service</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("Index", "Services"))
{
// TODO: validate up front
<div class="row">
Service Title : #Html.TextBoxFor(x => x.ServiceTitle)
</div>
<div class="row">
ServiceDescription : #Html.TextAreaFor(x => x.ServiceDescription)
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save Changes</button>
</div>
}
</div>
</div>
</div>
</div>
The problem is when you click the button first time the
$('#serviceModal').modal(); function is being called before the modal load.
So, you need to call this $('#serviceModal').modal(); function after $('#AddServiceForm').load(url); is done. Means that ater loading the AddNewService.cshtml is completed then you can find your desired modal in you DOM. See for more in here http://api.jquery.com/load/
After that you can show the modal. Some times when you add any DOM elements achieved by ajax call added to you main DOM specially DOM with form elements; the DOM parser can't get it first time so use the body tag to find any child element. I have put a code bellow. Try with this :
$("#AddServiceForm").load(url, function(responseTxt, statusTxt, xhr) {
// debugger;
if (statusTxt == "success")
{
$('body #serviceModal').modal('show');
}
if (statusTxt == "error")
{
console.log("Error: " + xhr.status + ": " + xhr.statusText);
}
});

Asp.Net MVC 5 The ActionLink Only Calls The Action Method in The First Time When I Click on It

I'm working on an e-commerce website. What I'm trying to do right now is when users click on the "Open Modal" link, a modal dialog will open and show the product detail.
At the first time when I click on the ActionLink, it will call the QuickView action method in the Product controller and show the detail information of the product. However, when I click on the ActionLink for another product, it won’t call the QuickView action method. Also, the content of the modal dialog still displays the information of the previous product. Basically, the problem is that the action method only gets called in the first time that I click on the ActionLink. The action method won’t get called anymore when I click on the ActionLink again. When I right-click the page and inspect the element, I can see that the modal action link is generated correctly. I’m so confused about it. Please help.
The main view:
<div id="product">
#foreach (var product in Model.Products)
{
#Html.Partial("ProductSummary", product)
}
</div>
// The normal bootstrap modal with out any content in the modal-content div. Note that the id matches the data_target from the link
<div id="modal-container" class="modal fade product_view" tabindex="-1"
role="dialog">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
#section scripts {
// The normal bootstrap behavior is to only grab the content for the
// modal once, if you need to pull in different partial views then the data on
// the modal will have to be cleared.
<script type="text/javascript">
$(function () {
$('#modal-container').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
$('#modal-container .modal-content').empty();
});
});
// callback from form modal
function success() {
alert("Success!");
}
</script>
The product summary:
<div class="caption">
<h4 class="pull-right">#Model.Price.ToString("c")</h4>
<h4>
#Ajax.ActionLink(Model.Name, "ProductDetail", new { productId = Model.ProductID, returnUrl = Request.Url.PathAndQuery },
new AjaxOptions { UpdateTargetId = "content", InsertionMode = InsertionMode.Replace })
</h4>
</div>
<div class="space-ten"></div>
<div class="btn-ground text-center">
<button type="button" class="btn btn-primary" onclick="location.href='#Url.Action("AddToCart", "Cart", new { ProductId = Model.ProductID})'">
<i class="fa fa-shopping-cart"></i> Add To Cart
</button>
<div>
// Create a link that calls the controller method that returns the partial view
#Html.ActionLink("Open Modal", "QuickView", "Product", new { ProductId = Model.ProductID }, new
{
// Needed to link to the html of the modal
data_target = "#modal-container",
// Tells the bootstrap javascript to do its thing
data_toggle = "modal"
})
</div>
</div>
<div class="space-ten"></div>
</div>
The quick view:
<div class="modal-header">
<a href="#" data-dismiss="modal" class="class pull-right"><span
class="glyphicon glyphicon-remove"></span></a>
<h3 class="modal-title">#Model.Name</h3>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6 product_img">
<img
src="http://img.bbystatic.com/BestBuy_US/images/products/5613/5613060_sd.jpg"
class="img-responsive">
</div>
<div class="col-md-6 product_content">
<h3 class="cost"><span class="glyphicon glyphicon-usd"></span> #Model.Price </h3>
<div class="space-ten"></div>
<div class="btn-ground">
<button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-shopping-cart"></span> Add To Cart</button>
<button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-heart"></span> Add To Wishlist</button>
</div>
</div>
</div>
The action method in the product contorller:
public ActionResult QuickView(int productId)
{
Product prod = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
return PartialView(prod);
}
image of the inspect element
Make sure the modal content is empty before the action link tries to call the server.
You have javascript code which seems like it clears the modal content whenever the modal gets hidden. Is it possible that the modal still has content when you click an action link after the first time?
EDIT:
Try adding an onclick function that empties the modal content when the action link is clicked. So add the onclick property in your ActionLink call by changing your code like below:
change this:
$('#modal-container').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
$('#modal-container .modal-content').empty();
});
to:
var emptyModalContent = function() {
$('#modal-container').removeData('bs.modal').find('.modal-content').empty();
};
$('#modal-container').on('hidden.bs.modal', function () {
emptyModalContent();
});
and add onclick property to action link:
#Html.ActionLink("Open Modal", "QuickView", "Product", new { ProductId = Model.ProductID }, new
{
// Needed to link to the html of the modal
data_target = "#modal-container",
// Tells the bootstrap javascript to do its thing
data_toggle = "modal",
onclick = "emptyModalContent()"
})
Thanks everyone who gives me the suggestion. In order to fix the issue, I need to combine the solutions that provide by #Anthony McGrath, #ecKO and #Kumar_Vikas.
Here is the solution:
As #Anthony McGrath mention:
Change the script from:
$('#modal-container').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
$('#modal-container .modal-content').empty();
});
to:
var emptyModalContent = function() {
$('#modal-container').removeData('bs.modal').find('.modal-
content').empty();
};
$('#modal-container').on('hidden.bs.modal', function () {
emptyModalContent();
});
After that, follow #ecKO and #Kumar_Vikas' idea and change the action link that calls the action method from #Html.ActionLink to #Ajax.ActionLink.

MVC 4 partialview not displaying as modal dialog, instead displays as own page

I'm experimenting and trying to learn how to use more modal dialogs and less "view jumping". What I was trying to do is in the Home/Index is display the _join.cshtml partial view as a modal popup. Instead what I get is either
The browser redirecting to User/Join and displaying the popup (if I return full View from the User controller)
The partial view displaying as it's own page without the .js and .css support that's in the _Layout.cshtml view.
I've provided the code below and would appreciate untangling what I have so far.
Controller code
public class UserController : Controller
{
public ActionResult Join()
{
return PartialView("_join");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Join(Userprofile userprofile)
{
return PartialView("_join", userprofile);
}
}
The partial view named _join.cshtml
This resides in the "join" views folder
#model DPDP.Models.Userprofile
<div id="ModalUserJoin" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="ModalUserJoinLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="ModalUserJoinLabel">Create An Account</h3>
</div>
<div class="modal-body">
<div class="embed-responsive embed-responsive-16by9">
#using (Ajax.BeginForm("Join", "User", FormMethod.Post, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
/* Form elements have been removed to save space */
}
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
</div>
Javascript
This is to show the modal popup when the page loads and appears to work fine.
if ($('#ModalUserJoin').length > 0) {
$('#ModalUserJoin').modal('show');
}
The way you are trying to do it is incorrect.
Step to do it are ...
Load your Index Page
Make an ajax post request on an event like onload, onClick using javascript to the page User/Join
In ajax request you get the html string of the popup model
Then fire the popup show event in with the html string.
Bootstrap code to do so is this.(as i suppose you are using bootstrap)
$(document).ready(function(){
var userModel = {name: "Donald Duck",city: "Duckburg"};
$("#userButton").click(function(){
$.post("User/Join",userModel ,
function(data, status){
$('body').append(data);
$('#ModalUserJoin').modal('show');
});
});
});
Maybe this helps or maybe i misunderstood your problem :)

Dynamic modal with Bootstrap and PartialView (asp.net)

/**** SOLVED ****/
I had tried create a dynamic modal with result from a partial view using a modal of bootstrap script, but I not get success with it. This is not equals to the questions in 1 and 2.
This is my html PartialView (simple modal pattern)
#model Dictionary<int?, Tuple<string,string>>
<div class="modal fade" id="#ViewBag.IdModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Selecione o item desejado</h4>
</div>
<div class="modal-body">
<table id="tabPesquisa" class="table table-condensed">
<thead>
<tr><th>Código</th><th>Descrição</th></tr>
</thead>
<tbody>
#foreach (KeyValuePair<int?,Tuple<string,string>> item in Model)
{
var valores = item.Value;
<tr data-idreg="#item.Key"><td>#valores.Item1</td> <td>#valores.Item2</td></tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" id="btnSelecao"><span class="glyphicon glyphicon-check"></span> Pronto!</button>
</div>
</div><!-- /.modal-content -->
It is a generic view and receives various data dynamically. (obvious)
On my main html, I have more buttons to get differents datas for the partial view. Example:
<button class="btn btn-primary" data-toggle="modal" data-target="#modalLayout" data-inputs="#hdnIdLayout,#txtCodLayout,#txtDescLayout" data-urlsearch="#Url.Action("ListaPesquisar", "Exame")"><span class="glyphicon glyphicon-search"></span></button>
On my main javascript file I have the code:
Sistema.AbrirModal = function (urlSearch, target, fields) {
var arrayFields = fields.split(",");
var target = target.slice(1, target.length);
var objModal;
$.get(urlSearch, { idModal: target }, function (data) {
objModal = $.parseHTML(data);
console.log(objModal);
$("body").append(objModal);
$(objModal).modal(); //ERROR: Uncaught TypeError: Object [object Object] has no method 'modal'
});
};
$(document).ready(function () {
if($('[data-toggle="modal"]').length > 0) {
$('[data-toggle="modal"]').on("click", function () {
var target = $(this).data("target"); //#modalLayout"
var fields = $(this).data("fields"); //#htnIdLayout,#txtCodLayout,#txtDescLayout"
var urlSearch = $(this).data("urlsearch")//"#Url.Action("ListaPesquisar", "Exame")"
Sistema.AbrirModal(urlSearch, target, fields);
});
}
}
Well, if I use $(objModal).modal([show, hide, none]); get a error (comented in the line above), if not use it, nothing occurs.
Does anyone have an idea how to solve this issue so I do not need to create several for each modal window on my main page?
Thanks everyone.

Categories

Resources