Rendering Partial View on Button Click in ASP.NET MVC

Render partial view on button click

you don't have to pass complete name of HomeController, In Url.Action() we have to pass prefix of Controller name, when we create controller we have to add a postfix of Controller in mvc and when we use it in helpers we have to just pass Controller name without Controller postfix:

public class HomeController: Controller
{
public ActionResult doctorsview()
{
return PartialView("~/Views/_Doktor.cshtml", new Doktor());
}

}

Do like this:

$("#someDiv").load('@Url.Action("doctorsview","Home")');

and you should be placing it in respective Views directory of Controller, which is in this case Views -> Home

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}

Show partial view on button click mvc

Well as I can't comment here are some points I use to call partial views

  1. If you are using a "main view" or a "shared view", you only need to define the scripts on the main view, not in your partial.
  2. If you want a partial view to be loaded on click without any parameter you can call it and "hide it"

View

<div id="partial" style="display: none">
@{Html.RenderAction("PartialEditCompany"); }
</div>

Controller

[ChildActionOnly]
public ActionResult PartialEditCompany()
{
//stuff you need and then return the partial view
//I recommend using "" quotes for a partial view
return PartialView("inventoryList");
}

And then if you want to have your partial view show on click you only display the div containing the div.


But if you want to use your partial view with parameters you can do the following

Javascript

 function getview(parameter){
var url = "@Html.Raw(Url.Action("PartialEditCompany", "Controller", new { parameterID = "-parameter" }))";
url = url.replace("-parameter", parameter);
$('#partial').load(url);



/*Better code by October 11, 2017, you can use this instead of the 3 lines on top*/
/*
var url = "@Html.Raw(Url.Action("PartialEditCompany", "Controller", new { parameterID = "-parameter" }))";
url = url.replace("-parameter", parameter);
$.ajax({
url: url,
type: "GET",
cache: false,
success: function(result){
$("#partial").html(result)
},
error: function(){
//handle your error here
}
});
*/
}

With javascript you can call a partial view and pass the parameter to the controller. Of course you don't specify if you need parameters or not, but here are both solutions I use with partial views. And you call your javascript function onclick event if you want or as you may like. (or using data-attr on the tag, and the with javascript or jquery on the click event, get that data-attr value without creating, this could be the unobtrusive way)

<input type="button" value="Traži" id="loadData" onclick='getview(parameter)' />

Hope this help a little about partial views.

How can i render partial view as modal popup on button click?

The following example should help achieve your requirement of rendering partial view as modal popup using jQuery Ajax, please check it.

All.cshtml

@model IEnumerable<Venue>

@{
ViewData["Title"] = "All";
}

<h1>All</h1>

<table class="table table-hover">
<thead>
<th> Property Name </th>
<th colspan="2">Action</th>
</thead>
<tbody>
@foreach (var x in Model)
{
<tr>
<td>
@x.Name
</td>
<td>
<a class="btn btn-default btn-sm" id="@x.Id" onclick="Details(this.id)">Show</a>
</td>
</tr>
}
</tbody>
</table>

<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">Details</h4>
</div>
<div class="modal-body">
</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 Details(id) {
$.get("@Url.Action("ShowpopUp","Owner")/" + id,
function (data) {
$('.modal-body').html(data);
});

$("#myModal").modal("show");
}
</script>
}

ShowpopUp action

public IActionResult ShowpopUp(int id)
{
var venue = _context.Venues.FirstOrDefault(x => x.Id == id);

//specify the name or path of the partial view
return PartialView("_VenueDetail", venue);
}

_VenueDetail.cshtml (partial view under Views/Shared folder)

@model Venue

<h1>Venue Details</h1>

<h2>Id: @Model.Id</h2>
<h2>Name: @Model.Name</h2>

Test Result

Sample Image

how can I call partial view from button click event

Here is a working demo like below:

Model:

public class DeleteViewModel
{
public string ConfirmationTitle { get; set; } = "Delete confirmation";
public string ConfirmationMesssge { get; set; } = "Are you sure you want to Delete ?";
public Product Product { get; set; }
}
public class Product
{
public string productName { get; set; }
public int productPrice { get; set; }
public int quantity { get; set; }
}

View(Index.cshtml):

<button type="button" class="btn btn-danger m-1" data-toggle="modal" data-target="#exampleModal">
Delete
</button>
@await Html.PartialAsync("_Delete")

Partial View:

@model DeleteViewModel
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">@Model.ConfirmationTitle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
@Model.ConfirmationMesssge
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<form asp-action="Delete">
<input type="hidden" asp-for="Product.productName" />
<input type="hidden" asp-for="Product.productPrice" />
<input type="hidden" asp-for="Product.quantity" />
<input type="submit" value="Delete" class="btn btn-default" />
</form>
</div>
</div>
</div>
</div>

Controller:

public async Task<IActionResult> Index()
{
var model = new DeleteViewModel() {
Product= new Product()
{
productName="aa",
productPrice=34,
quantity=2
}
};
return View(model);
}
[HttpPost]
public IActionResult Delete(Product product)
{
//do your stuff..
return Json("OK");
}

Result:
Sample Image

Partial view render on button click

The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:

<script src="@Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:

<input type="button" value="Buy" data-url="@Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="@Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />

and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:

$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});

or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:

@Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
@Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })

and if you want buttons instead of anchors you could use AJAX forms:

@using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
@using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}

From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.

Call Partial View with Modal using onClick in a button ASP.NET mvc

Example:

<div class="modal" id="livestream_scanner" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Search Barcode Scanner</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal-body">
<div id="qr-reader" style="width:450px"></div>


<div id="qr-reader-results" style="margin-bottom: 25px;"></div>

</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Then function

function showModal() {

$.ajax({
url: "/PurchaseOrder/Barcode",
dataType: 'html',
beforeSend: function () {

},
success: function (data) {

$('#modal-body').html(data);
$('#livestream_scanner').modal('show');
}
});
}


Related Topics



Leave a reply



Submit