Field not being found in view component - c#

Ok So this works fine in a view model but when i move it out to a view component it doesnt.
#foreach (var notes in Model) {
<tr>
<td>#notes.LastModifedDate</td>
<td>#notes.LastModifiedBy</td>
<td>#notes.Notes </td>
<td>
<a class="btn btn-app">
<i class="fas fa-edit"></i> Edit
</a>
|<p>#notes.Id</p> <i class="glyphicon glyphicon-trash"></i>Delete
</td>
</tr>
}
This is my Model in the same view component
<div id="deleteLink" class="modal fade" role="dialog">
<div class="modal-dialog">
#using (Html.BeginForm("DeleteNotes", "MISObjects", FormMethod.Post)) {
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete Record!</h4>
</div>
<div class="modal-body">
Are you sure you wish to delete this record ?.
<!--this is how to pass the id through-->
<input type="text" name="linkId" id="linkId" />
</div>
<div class="modal-footer">
<button type="submit" id="btnSubmit" class="btn btn-danger"
onclick="$('#testForm').submit()">
Yes
</button>
<button class="btn btn-warning" data-dismiss="modal">No</button>
</div>
</div>
}
</div>
</div>
Here I am telling it to attach the notes Id here but for some reason its not finding the text field the notes id is being passed through the data-id="#notes.Id" of the button above.
#section Scripts
{
<script>
function deleteModal(id) {
alert(id);
$("#linkId").val(id);
}
function EditModal(id) {
$("#editMode").val(id);
}
</script>
}
I am getting the following error I presume this will be something to do with jquery not ready at this point.

Here is a worked demo to use view component:
TestViewComponent.cshtml:
#{
ViewData["Title"] = "TestViewComponent";
}
<h1>TestViewComponent</h1>
<div>
#await Component.InvokeAsync("Notes", new List<notes> { new notes { Id = "1", Notes = "note1", LastModifedDate = "2020/01/01", LastModifiedBy = "Joy" }, new notes { Id = "2", Notes = "note2" }, new notes { Id = "3", Notes = "note3" } })
</div>
#section Scripts
{
<script>
function deleteModal(id) {
alert(id);
$("#linkId").val(id);
}
function EditModal(id) {
$("#editMode").val(id);
}
</script>
}
Shared/Components/Notes/Default.cshtml:
#model IEnumerable<notes>
#foreach (var notes in Model)
{
<tr>
<td>#notes.LastModifedDate</td>
<td>#notes.LastModifiedBy</td>
<td>#notes.Notes </td>
<td>
<a class="btn btn-app">
<i class="fas fa-edit"></i> Edit
</a>
|<p>#notes.Id</p> <i class="glyphicon glyphicon-trash"></i>Delete
</td>
</tr>
}
ViewComponents/Notes:
public class Notes:ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(List<notes> list)
{
return View(list);
}
}
Result:

You should use jquery's event binding instead of on click.
First update your anchor tag by adding additional class.
<i class="glyphicon glyphicon-trash"></i>Delete
Then ensure that the #section Scripts block is on the main view not the partial view. Then bind the class using the following
<script>
$(window).on("load", function () {
$(".delete-notes").on('click', function () {
alert($(this).attr("data-id"));
});
function EditModal(id) {
$("#editMode").val(id);
}
})
</script>

Related

Pass an id value from the model into a modal form using data-url="#Url.Action"

I have a form that displays a persons title and name.It shows a lot more than that, but this is the bit I am asking about.
I have a person table.
If the user wants to change the person details, is it possible to open up a pop up modal form that lists all the persons in the person table, so that the user can either select an existing person, or insert a new person and when the user closes the pop up, the main form is populated with the selected/new persons details?
I am using ASP.NET Core MVC 5 and EF Core 5.
Any help or pointing to a tutorial would be a great help, thanks.
UPDATE -
I have tried the following -
I have created a modal partial view -
#model Person
<div class="modal fade" id="personModal" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="personModalLabel">Persons</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<table class="table table-bordered table-striped table-hover">
<tbody>
#foreach (var pers in ViewBag.PersonList)
{
<tr>
<td style="display:none">#pers.Id</td>
<td class="text-left">
<a asp-action="details" asp-controller="admin" asp-route-id="#pers.Id" title="Click to select vaccination centre">#pers.Title.Description</a><br />
</td>
<td class="text-left ">
#pers.Forename
</td>
<td class="text-left ">
#pers.Surname
</td>
</tr>
}
</tbody>
</table>
<br />
<div class="form-row">
<label asp-for="TitleId" class="control-label col-md-2">Title</label>
<div class="col-md-4 mb-2">
<select asp-for="TitleId" asp-items="#(new SelectList(ViewBag.TitleList, "Id", "Description"))" style=" width: 363px; height: 37px"></select>
<span asp-validation-for="TitleId" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<label asp-for="Forename" class="control-label col-md-2">Forename</label>
<div class="col-md-4 mb-2">
<input asp-for="Forename" class="form-control" maxlength="100" />
<span asp-validation-for="Forename" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<label asp-for="Surname" class="control-label col-md-2">Surname</label>
<div class="col-md-4 mb-2">
<input asp-for="Surname" class="form-control" maxlength="100" />
<span asp-validation-for="Forename" class="text-danger"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save</button>
</div>
</div>
</div>
</div>
I have added the following script to site.js -
$(function () {
var placeHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function(data) {
placeHolderElement.html(data);
placeHolderElement.find('.modal').modal('show');
})
})
placeHolderElement.on('Click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
placeHolderElement.find('.modal').modal('hide');
})
})
})
And the controller -
[HttpGet]
public IActionResult Create()
{
List<Person> personList = _personRepository.Persons.ToList();
ViewBag.PersonList = personList;
List<Title> titleList = _titleRepository.Titles.ToList();
ViewBag.TitleList = titleList;
Person pers = new Person();
return PartialView("_PersonModalPartial", pers);
}
[HttpPost]
public IActionResult Create(Person pers)
{
_personRepository.CreatePerson(pers);
List<Person> personList = _personRepository.Persons.ToList();
ViewBag.PersonList = personList;
List<Title> titleList = _titleRepository.Titles.ToList();
ViewBag.TitleList = titleList;
return PartialView("_PersonModalPartial", pers);
}
I call the modal with the the following in my main form -
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create")" >Insert</button>
The above code shows the modal and populates the table.
However nothing happens when you press save!?
UPDATE 2 -
I changed the button in the modal for to
input type="submit" value="Submit" name="Submit" class="btn btn-success float-right" id="SubmitForm" />
And then changed the form tag in my modal form to -
<form method="post" asp-controller="Admin" asp-action="Create">
That worked.
Now I am wondering how you can pass the id value of the model into the Modal form using the data-url part of the calling button?
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create")" >Insert</button>
You can use #Url.Action("Create",new { id=xxx}),here is a demo:
Html(I use "sss" as a sample data of id):
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create1",new { id="sss"})">
Insert
</button>
js:
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeHolderElement.html(data);
placeHolderElement.find('.modal').modal('show');
})
})
Controller:
public IActionResult Create1(string id) {
return Ok();
}
result:
Update:
If you want to use #Model.Id:
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create1",new { id=Model.Id})">
Insert
</button>

ASP.Net Core 3.1 - passing value to partial view Modal From Controller?

I want to delete a record from table and I sent CategoryId with this code:
Main view :
<a data-toggle="modal" data-target="#Deletemodal" onclick="Func_LoadPv('#item.CategoryId')" class="btn btn-danger btn-xs">delete</a>
function Func_LoadPv(Cid) {
$.get("/AdminPanel/Category/ShowPartialView?CategoryId=" + Cid, function (res) {
$("div.modal-body").append(res);
});
}
Controller :
public IActionResult ShowPartialView(Guid CategoryId)
{
return PartialView("_DeleteMainCategory", CategoryId);
}
How can I get this value that is sent from the controller to the partial Modal?
And the problem I have is that the modal only opens once ?
How can I get this value that is sent from the controller to the partial Modal?
You can specify a model for your partial view _DeleteMainCategory.cshtml, like below.
#model Guid
<h1>DeleteMainCategory Partial View</h1>
#*content here*#
<h2>#Model</h2>
the problem I have is that the modal only opens once
The following sample with testing data work well for me, you can check and compare it with yours.
<table>
<tbody>
#foreach (var item in Model)
{
<tr>
<td> #rowCount</td>
<td>#item.CategoryTitle</td>
<td>#item.IconCategory</td>
<td>
<a data-toggle="modal" data-target="#Deletemodal" title="delete"
class="btn btn-danger btn-xs" onclick="Func_LoadPv('#item.CategoryId')">delete</a>
</td>
</tr>
}
</tbody>
</table>
<div id="Deletemodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
#*modal body here*#
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section scripts{
<script>
function Func_LoadPv(Cid) {
$.get("/AdminPanel/Category/ShowPartialView?CategoryId=" + Cid, function (res) {
$("div.modal-body").html(res);
});
}
</script>
}
Test Result
I solved
Modal :
<div id="deletemodal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">delete category</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="bodyModal" class="modal-body">
</div>
</div>
</div>
JQuery :
function DeleteCategory(id) {
$.ajax({
url: "/AdminPanel/Category/DeleteCategory/" + id,
type: "Get",
data: {}
}).done(function (result) {
$('#deletemodal').modal('show');
$('#bodyModal').html(result);
});
}
Controller :
public IActionResult DeleteCategory(Guid? id)
{
return View();
}
[HttpPost]
public IActionResult DeleteCategory(Guid id)
{
_admin.DeleteMainCategory(id);
return RedirectToAction("ShowMainCategory", "Category");
}
Partial View :
<form asp-action="DeleteCategory" class="form-padding">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<h5 class="text-center">Are You Sure ?</h5>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-info waves-effect">delete</button>
<button type="button" class="btn btn-danger waves-effect"
data-dismiss="modal">
cancel
</button>
</div>

Modal in foreach returning the same data for each modal

i am trying to populate modals with different data, i create the modals buttons using a foreach loop and then i want to apply the relevant data to the right modal.
The problem i have is that the modal is showing the same data for each modal button. How can i make this unique? When its doing its loop its actually placing the correct info but when the page loads its only showing one type of data for every modal.
#foreach (DataRow row in Model.Tables[0].Rows)
{
<tr>
<td>#row["SerialNumber"]</td>
<td>#row["DtTmGenerated"]</td>
<td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal">View Error</button>
</td>
</tr>
}
</thead>
<tbody></tbody>
</table>
#if (Model.Tables[0].Rows.Count != 0)
{
<script type='text/javascript'>
window.onload = function() {
document.getElementById("cssClass").style.display = 'none';
}
</script>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title justify-content-center">Panda Error information</h4>
</div>
<div class="modal-body">
#foreach (DataRow row in Model.Tables[0].Rows)
{
var test = Convert.ToString(row["FriendlyError"]);
if (test != "No Error" )
{
<p>#row["FriendlyError"]</p>
}
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
I'm a bit late but I had the same problem today and I managed to fix it :D
The problem is the ID of the modal. In each new loop pass your modal is created with the same ID.
In other words: Your values, which come into the modal always change, but because the ID is static, all further modals get the same values as in the first one, because all have the same ID. Try this:
Add this code right after your model (#model ...)
#{
int ModalId = 0;
}
Then change the ID in the button that opens your modal:
data-target="##ModalId"
In the line before you close your foreach, add this
#(ModalId++)
Change your modal to this and put it into your foreach so that it looks like this:
#foreach (DataRow row in Model.Tables[0].Rows)
{
<tr>
<td>#row["SerialNumber"]</td>
<td>#row["DtTmGenerated"]</td>
<td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="##ModalId">View Error</button>
<!-- Modal -->
<div id="#ModalId" aria-labelledby="#ModalId" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title justify-content-center">Panda Error information</h4>
</div>
<div class="modal-body">
#foreach (DataRow row in Model.Tables[0].Rows)
{
var test = Convert.ToString(row["FriendlyError"]);
if (test != "No Error")
{
<p>#row["FriendlyError"]</p>
}
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
#(ModalId++)
}
</thead>
<tbody>
</tbody></table>
#if (Model.Tables[0].Rows.Count != 0)
{
<script type='text/javascript'>
window.onload = function() {
document.getElementById("cssClass").style.display = 'none';
}
</script>
}
</body>
</html>
In summary: Wherever you had "myModal" as ID, you must replace it with #ModalId

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

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