How do I render my partialview inside my main view or can I update the values in another way? - asp.net-core

I have the following problem: So I built a search function for an OrderId in Nopcommerce and I want to update two values (Buyer Name) and (Purchase Reason) in a table in my main view instead of how it is now, where I render them in a partial view but it appears on the main page.
Example:
How it is at the moment after I click search button :
My controller that renders the partial view:
And here:Part of my SearchResult.cshtml partial view where the values appear
I want it to appear somewhere here (My startview.cshtml as you can see I tried some things but nothing seems to work, Ill delete those)
Thank you in advance!

You can achieve this using ajax call.
var request = {
OrderId: $('#OrderId').val(),
}
$.ajax({
url: "/Home/DisplayBuyerName",
type: "GET",
data: request,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
$("#SearchResult").html('').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
return false;
}
});
html:
<div id="SearchResult"> </div>
So now your partial view is placed in SearchResult div.

Related

Response.Redirect not changing URL

After clicking an element on my webpage, I get the expected behavior from Response.Redirect in the trace, the break point on the expected page gets hit and proceeds to process normally. However when I'd expect the new page to be loaded, the display in the browser is not changed. It looks and behaves like the click brought you back to the same page.
I've moved the redirect call out of a try-catch block, and have tried different combinations of true/false as the second parameter with HttpContext...CompleteRequest()
What might prevent a page from being loaded after a call from Response.Redirect and the Page_Load sub completes?
Edit:
The site uses css and javascript to create a hoverable dropdown menu containing self referencing links, see below. I have tried using Chrome's dev tools to see what the network was processing. As far as I can tell from reading the Network Tab the click was creating the correct call; status 200, type xhr. xhr was the only thing that I found odd, but it looks like this is simply a reference to ajax? This leaves me in the same position. I am telling the site to redirect to new url, and I see the network take a request for that url, but the url in the address bar doesn't change; not the displayed page.
$(document).on('click','.navigation', function () {
loadItems($(this).attr('id'), $(this).attr('itemName'));
return false;
}
);
var loadItems = function (id, itemName) {
var editInfor =
{
"method": "getChildItems",
"id": id
};
$.ajax
(
{
type: "POST",
url: $.url,
dataType: "json",
data: JSON.stringify(editInfor),
success: function (jsonReply) {
$("#chkEnabled").attr('checked', jsonReply.enabled)
if (jsonReply.method == 'getChildItems') {
$("#childrens").html('');
var html = '<table>'
if (jsonReply.successfull) {
$.each(jsonReply.children, function (i, item) {
html += '<tr><td><span class="children">' + item.text + '</span></td><td><a class="moveItemUp btn" href="#" id="moveItemUp' + item.id + '">Move Up <i class="icon-circle-arrow-up"></i></a> <a class="moveItemDown btn" href="#" id="moveItemDown' + item.id + '">Move Down <i class="icon-circle-arrow-down"></i></a></td><td>Remove</td></tr>'
});
}
html += '</table>'
$($.childrens).html(html);
}
}
}
);
Please try this:
$.mobile.changePage( "/Exmaple.aspx", {
transition: "pop"
});

MVC freeze, page is not responding for few seconds

when I added new dropdown to my view. This dropdown is filled with list from model. Model is loaded in Index action with high ammount of rows oround 4k. Problem is now that when I run the page, it freeze for like 5 seconds, before dropdown is filled, I mean my whole website is not responding. What can I do?
Either you can fill you drop down using ajax call after your page is loaded and show any small progress bar over the drop down while drop down is being loaded.
You will have to create an another action method that will only return the drop down element. and on document ready you will have to make an ajax call to that action method and on the success of ajax call load drop down items in drop down. :
$(document).ready(function(){
$.ajax({
url: //Url to your action method along with the student name in query string,
type:get,
dataType: "json",
complete: function() {
//remove progress bar.
},
beforeSend: function() {
//Show progress bar.
},
success: function (data) {
//fill second drop down like:
//$("#secondDropDown").append('<option value="' + anyvalue + '">' + anyText + '</option>');
}
});
});

using modal for each item in a list in yii framework

There is a list of patient data using a "TbGridView" widget,
Now, I want to use modal widget for each one of the patient here, so, that
the patient id is passed to the modal for each patient with patient id.
I had tried this, but, I am being unable to pass each patient id to the modal form.
Any response related to this would be very helpful.
Thank you.
Actually there is no direct way of doing that I mean that you cant render dynamic data by passing an id. Modal is static.
You can use ajax call for that to retrieve data from database and render that data in your modal. Follow these steps
1. In your gridview use rowHtmlOptionsExpression to set id for specific row.
2. create an action in your controller to handle ajax call.
3. use jquery click event on TbGridView elements like
$('#mygrid table tbody tr td:not(:first-child)').on('click', function() {
var Url =<?php echo '"' . CController::createUrl('/user/default/viewMessageAjax') . '"'; ?>;
var id = $(this).parent().attr('id');
console.log($(this));
$.ajax({
url: Url,
data: {id: id},
success: function(data) {
$('.modal-body').html(data);
$('#myModal').modal('show');
}
});
})
jQuery('#mygrid >table>tbody>tr:first-child').live('click', function() {
return false;
})
above code is just an example, you can change it according to ur needs.

Asp.net MVC4 partial view loading inside popup

I am having an issue with a MVC4 app I have a view that has two partial view on it.
My main view is opening inside the popup. My screen open successfully with 2 partial view on a popup window.
Upper part of my view contains data entry/edit( partial view) and bottom part is display ( partial view).
Display part partial view contains web grid and eac a hyperlink ( edit and delete ) . when user click on edit , application should load the entry/edit view inside the same page.
My application should load entry/edit partial view on the same window .
Please suggest how to achieve this.
see the below code i am using on display view.
---------------------------------------------------------- First Partial view---
#model IEnumerable<Peabody.LMS.WebApp.ViewModels.AUTenement.TenementTypeLookupViewModel>
<div id="gridContent">
#{
var grid = new WebGrid(Model, defaultSort: "TypeCode", rowsPerPage: 10, ajaxUpdateContainerId: "gridContent");
}
#grid.GetHtml(tableStyle: "table",mode: WebGridPagerModes.All,
firstText: "<< First",
    previousText: "< Previous",
nextText: "Next >",
    lastText: "Last >>",
footerStyle: "foot-grid",
columns:
grid.Columns(
grid.Column("TypeCode",header:"TenementType Code"),
grid.Column("TypeDescription", header: "Tenement Description"),
grid.Column("Country", header: "Country"),
grid.Column("State", header: "State"),
grid.Column("LastModifiedBy", header: "Last Modified By"),
grid.Column("LastModifiedOn", header: "Modified On"),
grid.Column("Actions", "",#<a href='/TenementTypeLookup/LoadHeaderEdit/#item.TypeCode' ><img src="~/Images/edit-icon.png" alt='Edit' /></a>, style: "width:auto"),
grid.Column("", "",#<a href='/TenementTypeLookup/Delete/#item.TypeCode' ><img src="~/Images/Delete-icon.png" alt='Edit' /></a>, style: "width:auto")
))
</div>
------------------------------
the best way I have found is to load the partial with an ajax call.
$(document).on('click', '.btnDisplay', function(){
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: {
Field1: 'field1',
Field2: 'field2'
}
success: function (result) {
$('.targetDiv').html(result);
}
});
then on your controller
[HttpPost]
public PartialViewResult Action(string Field1, string Field2){
var model = //populate model from database
return PartialView("_PartialName", model);
}
so the ajax call will call the controller and pass whatever parameters you want. Then you can build the model and return the partial view. In the success of the ajax call it will take the returned partial view and put them into the whatever your target it (a div with class .targetDiv in this case)

Pass data-attribute value of clicked element to ajax settings

For an implementation of Magnific Popup, I need to pass a post id to the ajax settings. The post id is stored in a data attribute of the element to which Magnific Popup is bound. I would like this to work:
html element:
<a data-id="412">Clicke me</a>
Javascript:
$('.element a').magnificPopup({
type: 'ajax',
ajax: {
settings: {
url: php_array.admin_ajax,
type: 'POST',
data: ({
action:'theme_post_example',
id: postId
})
}
}
});
Where postId is read from the data attribute.
Thanks in advance.
$('.element a').magnificPopup({
callbacks: {
elementParse: function(item){
postData = {
action :'theme_post_example',
id : $(item.el[0]).attr('data-id')
}
var mp = $.magnificPopup.instance;
mp.st.ajax.settings.data = postData;
}
},
type: 'ajax',
ajax: {
settings: {
url: php_array.admin_ajax,
type: 'POST'
}
}
});
Here is how to do it:
html:
<a class="modal" data-id="412" data-action="theme_post_example">Click me</a>
jquery:
$('a.modal').magnificPopup({
type: 'ajax',
ajax: {
settings: {
url : php_array.admin_ajax,
dataType : 'json'
}
},
callbacks: {
elementParse: function() {
this.st.ajax.settings.data = {
action : this.st.el.attr('data-action'),
id : this.st.el.attr('data-id')
}
}
},
parseAjax: function( response )
{
response.data = response.data.html;
}
});
php
function theme_post_example()
{
$id = isset( $_GET['id'] ) ? $_GET['id'] : false;
$html = '<div class="white-popup mfp-with-anim">';
/**
* generate your $html code here ...
*/
$html .= '</div>';
echo json_encode( array( "html" => $html ) );
die();
}
As this answer was the original question regarding inserting data into Magnific's ajax call, I'll post this here.
After many hours of trying to figure this out, you should know that if you're using a gallery with the ability to move between gallery items without closing the popup, using elementParse to set your AJAX data will fail when you visit an item after already viewing it (while the popup is still open).
This is because elementParse is wrapped up in a check that it makes detect if an item has already been 'parsed'. Here's a small explanation as to what happens:
Open gallery at item index 2.
Item has not been parsed yet, so it sets the parsed flag to true and runs the elementParse callback (in that order). Your callback sets the ajax options to fetch this item's data, all is well.
Move (right) to item index 3.
Same as above. The item has not been parsed, so it runs the callback. Your callback sets the data. It works.
Move (left) back to item index 2.
This time the item has been parsed. It skips re-parsing the item's element for assumed potential performance reasons.Your callback is not executed. Magnific's ajax data settings will remain the same as if it were item index 3.
The AJAX call is executed with the old settings, it returns with item index 3's data instead, which is rendered to the user. Magnific will believe it is on index 2, but it is rendering index 3's data.
To resolve this, you need to hook onto a callback which is always executed pre-ajax call, like beforeChange.
The main difference is that the current item isn't passed through into the callback. Fortunately, at this point, magnific has updated their pointers to the correct index. You need to fetch the current item's element by using:
var data = {}; // Your key-value data object for jQuery's $.ajax call.
// For non-closures, you can reference mfp's instance using
// $.magnificPopup.instance instead of 'this'.
// e.g.
// var mfp = $.magnificPopup.instance;
// var itemElement = mfp.items[mfp.index].el;
var itemElement = this.items[this.index].el;
// Set the ajax data settings directly.
if(typeof this.st.ajax.settings !== 'object') {
this.st.ajax.settings = {};
}
this.st.ajax.settings.data = data;
This answer can also be used as a suitable alternative to the currently highest voted, as it will work either way.
You may use open public method to open popup dynamically http://dimsemenov.com/plugins/magnific-popup/documentation.html#public_methods
postId = $(this).attr('data-id')
$(this) retrieve the current element (the link you clicked on), and attr the value of the specified attribute.