Display a "Details" view as a modal popup - asp.net-mvc

I have this code to show info about a certain product registered in my database.
Button that triggers my Details Controller:
#Html.ActionLink("Details", "Details", new { id = prod.ID }, new { #class = "btn btn-danger" }) |
Controller code
public ActionResult Details(int? id)
{
PRODUCTS pRODUCTS = db.PRODUCTS.Find(id);
if (pRODUCTS == null)
{
return HttpNotFound();
}
return View(pRODUCTOS);
}
I want to display that "Details" view in a modal popup. I tried to create my modal in the same view where i have my "Details" button, but i can't pass my product id to the controller and it only shows me an empty view.

To show data inside a modal popup, you need an action method which returns HTML markup needed for the modal popup. So the first step is to make an action method which returns a partial view result.
public ActionResult Details(int id)
{
var product = db.PRODUCTS.Find(id);
if (product== null)
{
return HttpNotFound();
}
return View(product);
}
In the above simple example, I am querying the entity and passing the entity object directly to my view using the PartialView method. If you have a view model for your view, please use that.
Now in the Details.cshtml view, we will write code to return the HTML markup needed for the modal popup. Since we are passing the PRODUCTS object to the view, we will make sure our view is also strongly typed to that type.
#model YourNamespaceHere.PRODUCTS
<div id="modal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"> Details</h5>
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h2>Hello from #Model.Name</h2>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In the above example, I am simply printing the Name property value of PRODUCTS object in the modal body. You may update it to render other properties as needed.
Now we will make some changes to our HTML markup being rendered for the product. We need the click event on the details link to open the modal dialog. So let's first give some attributes to the link element, which we can later use to wireup the click event. Here I am going to add an additional CSS class to the links, modal-link.
#Html.ActionLink("Details", "Details", new { id = prod.ID },
new { #class = "btn modal-link" })
Now let's write some JavaScript code to listen to the click event on the link element with the modal-link CSS class, read the the href attribute value of the element and make an Ajax call to that URL and render the response of that call to build the modal dialog.
$(function () {
$('body').on('click', 'a.modal-link', function (e) {
e.preventDefault();
$("#modal").remove();
// Get the Details action URL
var url = $(this).attr("href");
//Make the Ajax call and render modal when response is available
$.get(url, function (data) {
$(data).modal();
});
});
});
I am using CSS class as the selector here, you can use any other selector as you wish

i think you should use jquery ajax to call action on click your button or action link and get your model as json result and return it then first clean your modal data and fill it with new result and at the end show your modal......

Related

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;
};

View call to another view in 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

Kendo ui MVC window modal making Ajax call with paramters to controller

I am new to Kendo and I am having a very hard time trying to do this. I followed this demo.
here and got it to work up the part that I wanted to have a text box and a send button in the window modal that the user would have to fill in and click send.
I am able to use Ajax to make the call to my controller but I can't get the information in the modal window to pass to the controller via FormCollection. Here's my window modal template:
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h5 data-idtest="1">#= Id #</h5>
<h2>#= TitleDisplay # - #= ArtistDisplay #</h2>
Input The Day:<input id="TheDayTextBox" name="TheDay" type="text" />
#using (Ajax.BeginForm("TheAction", "Search", new AjaxOptions { UpdateTargetId = "#=Id" }))
{
<button class="btn btn-inversea" title="Log outa" type="submit">Log Offsdfsaf</button>
}
</div>
Controller:
public ActionResult TheAction(string id, FormCollection form)
{
....
}
So how does Kendo pass data to controller inside a modal?
Try putting your input inside of the actual form:
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h5 data-idtest="1">#= Id #</h5>
<h2>#= TitleDisplay # - #= ArtistDisplay #</h2>
#using (Ajax.BeginForm("TheAction", "Search", new AjaxOptions { UpdateTargetId = "#=Id" }))
{
Input The Day:<input id="TheDayTextBox" name="TheDay" type="text" />
<button class="btn btn-inversea" title="Log outa" type="submit">Log Offsdfsaf</button>
}

ASP.NET MVC connect buttons to methods in controller

I have two buttons in my view and I want to add some information to my database when user click each of these two buttons.
<div class="container">
<div class="btn-group" style="text-align: center">
<h2>
<font color="gray">Please Choose your Department</font></h2>
<div class="btn-toolbar pagination-centered">
<div class="btn-group">
<button id="SARU" class="btn btn-inverse btn-large">
SARU</button>
<div class="span1">
<button id="AN" class="btn btn-inverse :hover btn-large">
AN</button>
</div>
<script type="text/javascript">
$('#SARU').click(function () {
UserController.AddGroupSARU();
});
$('#AN').click(function () {
UserController.AddGroupAN();
});
</script>
</div>
</div>
</div>
and the AddGroupSARU and AddGroupAN methods are in Usercontroller . how should I do this ?
Use jquery ajax to make a call to the action method. You can use the $.post method.
$(function(){
$('#SARU').click(function () {
$.post("#Url.Action("AddGroupSARU","User")");
});
});
The Url.Action helper method will resolve the proper path to the action method and render it. If you look at the View source of the page you will see the js code like
$(function(){
$('#SARU').click(function () {
$.post("User/AddGroupSARU");
});
});
Decorate your action method with [HttpPost] attribute as well. It is a good idea to keep your data updation/insertion/DELETION operations in a HttpPost action method so that boats/search engine won't destroy your data.
[HttpPost]
public ActionResult AddGroupSARU()
{
// do something and return something
}
u can use Jquery and ajax. i try to use Razor to connect button to methods in controller
like this..
<input style="width:100px;" type="button" title="EditHotelDetail" value="EditDetails" onclick="location.href='#Url.Action("Edit", "Hotel")'" />
"Edit" is name of your methods
"Hotel" is name of your controller

Pass constant value and variable (input) text from View to Controller

I'm fairly new to ASP.NET MVC and still getting used to some of the concepts.
I understand that to pass the value of a text box in the View back to the Controller, I can use Html.BeginForm and give the text box the same name as the corresponding parameter in the Controller Action.
Here's my situation: I have 2 buttons. I want them to call the same Action in the Controller. I want them to both pass the value for the text box (i.e. the "searchText").
However, I want one of the buttons to pass "false" for the parameter isQuickJump and I want the other button to pass "true" for the parameter isQuickJump.
Here is my View:
#using (Html.BeginForm("SearchResults", "Search", FormMethod.Get)) {
<div id="logo" class="centered">
<a href="SearchResults">
<img alt="Search" src="../../Content/themes/base/images/Search.jpg" />
</a>
</div>
<div id="searchBox" class="centered">
#Html.TextBox("searchText", null, new { #class = "searchTextBox" })
</div>
<div id="buttons" class="centered">
<input type="submit" id="searchButton" value="Search" class="inputBtn" />
#Html.ActionLink("Quick Jump", "SearchResults", "Search", new { isQuickJump = true }, new { #class = "btn" })
</div>
}
Controller:
public ActionResult SearchResults(string searchText, int? page, int? size, bool? isQuickJump, GridSortOptions sort)
{
var items = GetSearchGrid(searchText, page, size, sort);
if (Request.IsAjaxRequest())
return PartialView("_SearchResultsGrid", items);
return View(items);
}
Any suggestions on how to do this?
I appreciate your help!
Just use 2 submit buttons with the same name and different value:
<div id="buttons" class="centered">
<button type="submit" name="isQuickJump" value="false">Search</button>
<button type="submit" name="isQuickJump" value="true">Quick Jump</button>
</div>
Depending on which button is clicked the corresponding value will be sent to the server for the isQuickJump parameter. And since both are submit buttons, they will also submit all other input fields data to the server (which was not the case with the anchor that you used as the second button).

Resources