View call to another view in MVC - asp.net-mvc

I have created a popup view(EmployeeRegistration.cshtml) using Bootstrap for registration and its Action method. But I want to get this popup view from another view(EmployeeList.cshtml). Can I do it? If yes then How? Any code please.
//EmployeeList.cshtml
#Html.ActionLink("Create New", "Registration", "Registration", new
{
#class = "openDialog",
data_dialog_id = "aboutDialog",
data_dialog_title = "Create Employee"
})
<div id="gridposition" style="width: 100%;">
#{
#grid1.GetHtml(mode: WebGridPagerModes.All,
//code to display employee list on grid
}
</div>
Below is Registration.cshtml
#using (Html.BeginForm())
{
<div class="modal fade mymodal" id="openDialogDiv">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
//code here to pop up
</div>
</div>
</div>
I want to show popup on click of ActionList as shown above

Create a a div in your EmployeeList.cshtml to hold the html returned from Registration.cshtml
<div id="result"></div>
Make your Registration.cshtml as a partial view.
Use this anchor tag.
Create New
Make an ajax request to get the popup content and onsuccess, populate the div with the returned html and open the modal popup.
<script>
function funName()
{
$.ajax({
url: 'yoururl',
type: 'GET',
dataType: 'html',
success: function(data) {
$('#info').html(data);
$('#mymodal').modal('show');
},
error: function() {}
});
}

I think There are two options :
1. Forget about Registration.cshtml and put the below code in EmployeeList.cshtml:
<button type="button" class="openDialog">Create New</button>
<form class="modal fade mymodal" id="openDialogDiv" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
//code here to pop up
</div>
</div>
</div>
</form>
then show the form using jquery:
$('.openDialog').click(function(){
$('#openDialogDiv').modal();
});
2.create new action method in your controller which returns EmployeeRegistration.cshtml as partial view, let me name it DisplayRegistration() , now you can use ajax call, to DisplayRegistration() and display EmployeeRegistration.cshtml.
Please note that I changed Html.ActionLink to <button> tag

Related

ASP.NET Core MVC - Opening a Bootstrap modal view using a hyperlink

I am creating an ASP.NET (version 5) Core MVC application where I have a list of items. I try to make it so that when you click on an item it opens a (Bootstrap) modal view with the item's details (from another view). However, it seems like a hyperlink doesn't open the modal but instead opens the page itself (so not inside the modal). I got it working with a button, but I would like to make the user click on an item itself instead of a button.
This is the list item that I would like the user to be able to click on (the button is for testing):
I have the following page:
#model DetailsPatientFileViewModel
#section Scripts {
<script type="text/javascript">
$("#addBtn").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
$("#detailCard").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
</script>
}
<div class="patient-file-details-container">
<div class="title-container">
<h4>Treatments</h4>
<!-- This works just fine: -->
<button class=" btn-primary btn-primary" asp-controller="Treatment" asp-action="Create" asp-route-patientId="#Model.PatientId" data-toggle="ajax-modal" data-target="add-treatment" id="addBtn">Add</button>
</div>
<div id="component">
<!-- My list view component: -->
#await Component.InvokeAsync("TreatmentList", new { patientFileId = #Model.PatientFile.Id })
</div>
<!-- My modal: -->
<div id="Modal" class="modal fade">
</div>
</div>
The list view component (I also tested it with a button, see comment):
<ul class="card-list">
#foreach (var treatment in Model)
{
<li class="list-item-card">
<!-- Doesn't work: -->
<a asp-controller="Treatment" asp-action="Details" asp-route-id="#treatment.Id" data-toggle="ajax-modal" data-target="Modal" id="detailCard">
<h5>#treatment.Type</h5>
<p>#treatment.Date</p>
<p>#treatment.Employee.FirstName #treatment.Employee.LastName</p>
</a>
<!-- Does work: -->
<button asp-controller="Treatment" asp-action="Details" asp-route-id="#treatment.Id" data-toggle="ajax-modal" data-target="Modal" id="detailCard">Details</button>
</li>
}
</ul>
And finally the Details.cshtml (the to be opened view in the modal):
#using Core.Domain
#model Treatment
#{
Layout = null;
}
<h3>#Model.Type</h3>
<div class="modal-diaglog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="detailTreatmentLabel">Treatment details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>#Model.Date</p>
<p>#Model.Description</p>
<p>#Model.Employee.FirstName #Model.Employee.LastName</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
Does anyone know if it is possible to open a seperate view in a modal using a hyperlink? And if not, would there be a workaround to still be able to click on the list item itself?
Thank you in advance!
You can try to call a js function when click hyperlink:
ViewComponent:
<ul class="card-list">
#foreach (var treatment in Model)
{
<li class="list-item-card">
<!-- Doesn't work: -->
<a href="javascript:Details(#treatment.Id)">
<h5>#treatment.Type</h5>
<p>#treatment.Date</p>
<p>#treatment.Employee.FirstName #treatment.Employee.LastName</p>
</a>
<!-- Does work: -->
<button asp-controller="Treatment" asp-action="Details" asp-route-id="#treatment.Id" data-toggle="ajax-modal" data-target="Modal" id="detailCard">Details</button>
</li>
}
</ul>
page js:
#section Scripts {
<script type="text/javascript">
function Details(id) {
$.ajax({
type: "GET",
url: "Treatment/Details?id="+id,
success: function (res) {
$("#Modal").html(res);
$("#Modal").modal();
}
});
}
$("#addBtn").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
$("#detailCard").click(function () {
$.ajax({
url: $(this).attr("formaction"),
}).done(function(res) {
$("#Modal").html(res);
$("#Modal").modal();
})
});
</script>
}

asp.net mvc ajax.beginform being sent as html.beginform

I have a partial view from which I would like to display a modal dialog with updated data. User clicking the div would trigger both the display of the modal and the ajax call for the content of the modal to be updated.
<div class="nMmenuItem" >
#using (Ajax.BeginForm("editItem","nMrestaurant",new { id = Model.ID },
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myModalDocument"
}, new { id = "ajaxEditItem" }))
{
<div data-toggle="modal" data-target="#myModal"
onclick="$('form#ajaxEditItem').submit();">
<div class="text-center">
#Model.name
</div>
</div>
}
</div>
I have a placeholder for the modal inside the parent view:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document" id="myModalDocument">
#Html.Partial("_editItem", new nMvMmenuItem())
</div>
</div>
But while the controller action is expecting an AjaxResquest, the controller is evaluating Request.IsAjaxRequest() as false.
public async Task<ActionResult> editItem(int? id)
{
if (Request.IsAjaxRequest())
{
return PartialView("_editItem", await db.nMmenuItems.FindAsync(id));
}
return View();
}
Which refreshes the whole view and prevents the modal from working.
I am bundling the following scripts in the _Layout.cshtml page:
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.unobstrusive*",
"~/Scripts/jquery.validate",
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"
Thanks for your help!
Check that you've got the unobtrusive ajax client scripts installed - your bundle pattern looks like it will pick them up if they are there, but I don't believe they are installed in the default project:
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
While the Ajax.BeginForm is included in the standard MVC project, the client scripts are not and these are what is responsible for loading the content without refreshing the whole page.
I found that attaching submit() to the form's onclick event would not perform an ajax request.
My solution is thus to remove Ajax.SubmitForm and instead deal with the click event in my js:
The updated view looks like this:
<div class="nMmenuItem">
<form method="get" action="#Url.Action("editItem","nMrestaurant",new { id = Model.ID })"
data-nM-ajax="true" data-nM-target="#myModalContent">
<div>
<div class="text-center">
#Model.name
</div>
</div>
</form>
In the js I will bind the form submission to the click event of the parent div:
$('.nMmenuItem').click(ajaxFormSubmit);
And the function that handles the form submission and opens the resulting modal dialog:
var ajaxFormSubmit = function () {
var $form = $(this).children('form:first');
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nM-target"));
$target.replaceWith(data);
$("#myModal").modal(dialogOpts);
});
return false;
};

Dragging file onto document body triggers modal with Dropzone.js

I want to duplicate the behavior for uploading images in Slack in my chat app.
Currently, you can click a button in the area where you enter a message, and that brings up a modal where you can drag and drop files using Dropzone.js. That’s great.
However, I also want the entire page (document body) to be a dropzone as well. So when you drag a file onto the screen, I want the previously mentioned modal to pop up, with the dragged file loaded.
I tried adding this to the bottom of the page, but no dice:
<script>
// Make whole page a dropzone for image uploads
new Dropzone("#body", { // Make the whole body a dropzone
url: "/upload/url", // Set the url
previewsContainer: "#modal-image-uploads .modal-body #previews" // Define the container to display the previews
});
Dropzone.options.filedrop = {
init: function () {
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
$('body').append("<%= escape_javascript(render :partial => 'rooms/modals/image_uploads') %>");
}
});
}
};
</script>
The error in the console is: Uncaught Error: Invalid previewsContainer option provided. Please provide a CSS selector or a plain HTML element.
Here's what the modal looks like:
<div class="modal fade" id="modal-image-uploads" tabindex="-1" role="dialog">
<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">Upload Image</h4>
</div>
<div class="modal-body">
<div id="previews" class="dropzone-previews"></div>
<form action="/file-upload"
class="dropzone"
id="my-awesome-dropzone"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>

ASP.net MVC and View inside bootstrap modal

I've been hitting a wall for awhile regarding this problem. I'm not sure how to do a postback in modal without refreshing the main view.
I have a view which has the following bootstrap modal
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal" 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"></h4>
</div>
<div class="modal-body">
#Html.Partial("~/Views/Kontakt/BasicCreate.cshtml", new IDE3_CRM.ViewModels.BasicKontaktViewModel())
</div>
</div>
</div>
BasicCreate View
#model IDE3_CRM.ViewModels.BasicKontaktViewModel
#{
Layout = null;
}
#using (Html.BeginForm("BasicCreate", "Kontakt", FormMethod.Post, new { id = "basicCreate" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.HiddenFor(model => Model.idFirma)
//Similar forms group are intentionally ommited, one below is left for the reference
<div class="form-group">
<label class="control-label col-md-2">Bilješke</label>
<div class="col-md-10">
#Html.TextAreaFor(model => model.Biljeske, new { #class = "form-control", #rows = "5" })
#Html.ValidationMessageFor(model => model.Biljeske)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Spremi" class="btn btn-default" />
</div>
</div>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('#basicCreate').submit(function () { // you can use any selector that match your form
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize()
}).done(function (data) {
// Do something when server returns success!
});
return false; // prevent the form submission
});
})
</script>
BasicCreate controller:
[HttpPost]
[ValidateAntiForgeryToken]
public void BasicCreate([Bind(Include = "idKontakt,idOvlasti,idFirma,Username,Password,Ime,Prezime,Funkcija,Tel1,Mob1,Fax,Email1,Adresa1,Grad,Drzava,PostanskiBroj,Biljeske,Aktivan")] BasicKontaktViewModel kontakt, int? idCompany)
{
if (ModelState.IsValid)
{
Kontakt _kontakt = new Kontakt();
_kontakt.Adresa1 = kontakt.Adresa1;
_kontakt.Aktivan = true;
_kontakt.Biljeske = kontakt.Biljeske;
_kontakt.Drzava = "Hrvatska";
_kontakt.Email1 = kontakt.Email1;
_kontakt.Funkcija = kontakt.Funkcija;
_kontakt.Grad = kontakt.Grad;
_kontakt.idFirma = kontakt.idFirma;
_kontakt.idOvlasti = 4;
_kontakt.Ime = kontakt.Ime;
_kontakt.Mob1 = kontakt.Mob1;
_kontakt.Password = kontakt.Password;
_kontakt.Prezime = kontakt.Prezime;
_kontakt.Tel1 = kontakt.Tel1;
_kontakt.Username = kontakt.Username;
db.Kontakt.Add(_kontakt);
db.SaveChanges();
}
}
Whenever I click submit inside modal whole view gets submitted and what I'd like to accomplish is to submit only BasicCreate. For the reference, BasicCreate controller fires ok, and new Kontakt gets created.
EDIT
I've been experimenting with variety of approaches and I was able to localize the problem but not the reason for it. It seems that BasicCreate controller does postback no matter what type I set as the return object whether it be void, ActionResult, an empty view... It always postbacks and redirects to /Kontakt/BasicCreate
You can use an AJAX call like this:
$('form').submit(function () { // you can use any selector that match your form
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize()
}).done(function(data){
// Do something when server returns success!
});
return false; // prevent the form submission
});
Then you might want to add validation or check server result

hold submit for modal dialog confirmation in mvc 5

I'm trying to display a modal dialog when data is submitted on my create view. I need the modal to force the submit to wait for user confirmation on the modal dialog. Then the data needs to be submitted. Below is my create view code using bootstrap 3.0 modal-dialog:
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="col-md-offset-2 col-md-10">
<input id="create" type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
<div id="modalBox" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">X</a>
<h1>Confirmation</h1>
</div>
<div class="modal-body">
<h6>Click YES to confirm</h6>
</div>
<div class="modal-footer">
<button id="noPost" class="btn btn-default" name="postConfirm" value="false" data-dismiss="modal">No Thanks</button>
<button id="yesPost" class="btn btn-primary" name="postConfirm" value="true" data-dismiss="modal">YES</button>
</div>
</div>
</div>
#section scripts{
<scripts>
$(function () {
var modalBox = function (e) {
e.preventDefault();
$("#modalBox").modal({ show: true });
};
$("#create").click(modalBox);
});
<scripts>
}
This does interrupt the submit function and brings up the modal dialog but I don't know how to submit the data back to the controller once a selection is made on the dialog. I have also tried using the jquery ui modal dialog with the script below:
<script>
$("#create").click(function (e) {
e.preventDefault();
$("#postModal").dialog("open");
});
$("#postModal").dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"No Thanks": function (data) {
$("#create").submit();
$(this).dialog("close");
},
"YES": function () {
$("#create").submit();
$(this).dialog("close");
}
}
});
</script>
This does bring up the modal dialog but I still can't get it to submit the model data back to the controller. Any help would be appreciated.
UPDATE
By inspecting the produced html I discovered my input fields resided within a form that I didn't put there. I suspect this is due to me using the #Html.ValidationSummary(true) or something built into MVC. So instead of using:
$("#create").submit();
I used:
$("form:first").submit();
To submit the first, and only form, on the page and it worked!
Change your create button type to type=button, and make it to just open modal view. And make your yespost button in modal div holder to type submit . Also you can try to put whole modal div holder inside your form-group div. Here you are making post before openning modal view. It s because your button have 2 logic task, separate those task and this should work.

Resources