Refresh Partial view - model-view-controller

I used #Html.RenderAction("_DisplayImages") to render a partial view.
#model List<Univems4.Models.ImageViewModel>
#foreach (var image in Model)
{
<div class="set">
<div class="header invisible">
<label class="edit">#image.Name</label>
<button class="close btnDeleteImage" title="Delete">×</button>
</div>
<img class="img-thumbnail edit" src="data:image/bmp;base64,#image.base64string" id="#image.Id" />
</div>
}
Upon button click, I want to refresh this partial view. The approach I tried is by using jQuery ajax get method.
$.get("/VmsMessage/_DisplayImages", null, function (data) {
//success
$('#bit').html(data);
}, "html");
The partial view was refreshed. but it no longer responds to the events. Why?
$(".set").hover(function (e) {
// do something
});
$(".edit").click(function (e) {
// do something
});

As the html will be genrated dynamically so events are not binded on DOM load you need to do event delegation:
$(document).on("mouseover",".set",function (e) {
// do something
});
$(document).on("click",".edit",function (e) {
// do something
});

Related

MVC Partial View Returns Whole Page Instead of Just the Partial

I have the following partial view named "_transactions":
<div id="section-transactions" class="documentsanchor">
</div>
<div>
<div class="row">
<div class="col-lg-12">
<div>
<h4 class="company-headings">#ViewBag.SecSymbol Transactions</h4>
</div>
<div>
</div>
</div>
I render it using
#{Html.RenderAction("Transactions", "Company");}
and this is the Transactions method from the Company controller:
public async Task<PartialViewResult> Transactions()
{
ViewBag.SecSymbol = "test";
return PartialView("_transactions");
}
It's on a page with other partial views.
This works fine. However, I have a button on the page that should get a new partial view and replace the current one. It makes an ajax call as follows
$("#btn_transactions").click(function (e) {
var url = "Company/Transactions";
$.ajax({
url: url,
success: function (result) {
alert(result);
$('#transTarget').html(result);
},
error: function () {
alert("Error occured");
}
});
})
The issue is that the whole page is returned in "result", that is, all partials as well as the layout, when all I want is the transactions partial. What am I doing wrong?
Add this code in partial view
#{
Layout=null;
}
Make sure you have the route set up in your configs -
routes.MapRoute("CompanyTransactions", "company/transactions", new { controller = "Company", action = "Transactions" });

reCAPTCHA : Grey out Submit button until backend interaction is finished

I've integrated reCAPTCHA and it is working fine, except for when the users are too quick to click the Submit button right after checking the "I'm not a robot" checkbox. It takes quite some time for reCAPTCHA to register the user action via Ajax, and if they click on Submit too quickly, the g-recaptcha-response is missing, and the validation fails.
Hence my question: how to I grey out the Submit button until g-recaptcha-response value is available?
<form id="capform" action="/captchaverify" method="POST">
<div class="g-recaptcha" data-sitekey="..."></div>
<p>
<input id="capsubmit" type="submit" value="Submit">
</form>
I ended up using the data-callback attribute as described in the documentation:
<form action="/captchaverify" method="POST">
<div class="g-recaptcha" data-sitekey="..." data-callback="capenable" data-expired-callback="capdisable"></div>
<p>
<input id="capsubmit" type="submit" value="Submit">
</form>
JavaScript (mootools-based, but the general idea should be clear):
function capenable() {
$('capsubmit').set('disabled', false);
}
function capdisable() {
$('capsubmit').set('disabled', true);
}
window.addEvent('domready', function(){
capdisable();
});
Here's an example that begins with the submit button disabled, and enables it once the callback is received from reCaptcha. It also uses jquery validate to ensure the form is valid before submitting.
var UserSubmitted = {
$form: null,
recaptcha: null,
init: function () {
this.$form = $("#form").submit(this.onSubmit);
},
onSubmit: function (e) {
if ($(this).valid()) {
var response = grecaptcha.getResponse();
if (!response) {
e.preventDefault();
alert("Please verify that you're a human!");
}
}
},
setupRecaptcha: function (key) {
UserSubmitted.recaptcha = grecaptcha.render('recaptcha', {
'sitekey': key,
'callback': UserSubmitted.verifyCallback
//'theme': 'light'//,
//'type': 'image'
});
},
verifyCallback: function (response) {
if (response) {
$(".visible-unverified").addClass("hidden");
$(".hidden-unverified").removeClass("hidden");
}
}
};
I call setupRecaptcha from the page with a named function that's part of the js include.
<script>
var recaptchaLoader = function () {
UserSubmitted.setupRecaptcha("yourkey");
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaLoader&render=explicit" async defer></script>
You could simplify this. I use it in a multi-tenant application with different keys, and UserSubmitted is actually part of a larger library. You can't usenamespaces (UserSubmitted.somefunction) as the onload param either (to my knowledge).

Knockout - load data into model with Ajax - not straight away

Here's a simplified example of my knockout model. The problem I'm having is that as soon as the page loads, the quiz is loaded. Why does it get run straight away and how can I stop it so that it only get's run when I want, say, on the click of a button?
Do I even need to use subscribe to do this?
HTML:
<h1>Test</h1>
<button class="btn btn-primary" data-bind="click: quizCount(quizCount() + 1)">
Click Me
</button>
<hr />
<div data-bind="visible: !loaded()">No Quiz</div>
<div data-bind="visible: loaded">Quiz Loaded!</div>
<hr />
<h3>Debug</h3>
<div data-bind="text: ko.toJSON(quizModel)"></div>
Javascript:
<script type="text/javascript">
var quizModel = { };
// DOM ready.
$(function () {
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
};
quizModel = new QuizViewModel();
quizModel.quizCount.subscribe(function (newCount) {
$.getJSON('#Url.Action("GetNew", "api/quiz")', function (data) {
quizModel.questions(data.Questions);
}).complete(function () {
quizModel.loaded(true);
});
});
ko.applyBindings(quizModel);
})
</script>
Subscribe is only used for listening to changes in an observable so it will run immediately as soon as the observable gets a value.
You need to add this function to your viewmodel as a method, likely to be called getQuestions:
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
self.getQuestions = function(){
$.getJSON('#Url.Action("GetNew", "api/quiz")', function (data) {
self.questions(data.Questions);
}).complete(function () {
self.loaded(true);
});
}
};
then you can easily have a button or something that binds to this method on click:
<button data-bind="click: getQuestions">Get questions</button>

.on('click') with ajax content from another ajax content

Trying to get an event triggered with ajax content whose parent elements were also ajax loaded.
<div id="content"><!-- NOT ajax-loaded -->
<div id="location"> <!-- #location IS ajax-loaded -->
<div id="add_location> <!-- #add_location IS ajax-loaded from a #location event -->
<input type="text" id="add_location_city_example" />
<input type="text" id="add_location_state_example" />
<input type="submit" id="add_location_confirm" />
</div>
</div>
</div>
$(function(){
$('#content').on('click', '#add_location_confirm', function(){
console.log('debug 1');
add_location();
// will not be called
});
$('#location').on('click', '#add_location_confirm', function() {
console.log('debug 2');
// will not be called either
add_location();
});
});
If I have onclick="add_location()" and function add_location() { console.log('debug 3); } in my .js then it will obviously be called BUT I then cannot get $('#add_location_city_example').val() because none of it will be in the dom.
NOTE: using 1.9.1
I've been using this for a while, makes it much easier to handle situations like you are describing + there is only one even assignment for pretty much all clicks on the page, including elements that will appear on the page in the future:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('#content')) {
e.preventDefault();
// do whatever
} else if (target.is('#location')) {
e.preventDefault();
// do whatever else
}
});
or in your case it would probably be more like this:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('#add_location_confirm')) {
e.preventDefault();
if (target.closest('#location').length == 0) { // not yet have location injected via ajax
// do something
} else {
// location has been injected, do something else
}
});

generating pop up when button is clicked

when a submit button is clicked i want to generate a pop up showing the list of items. The code i tried to create pop up is as follows:`
Index View:
<script type="text/javascript">
$('#popUp').Hide();
$('#button').click(function () {
$('#popUp').click();
});
</script>
<div class="left-panel-bar">
#using (Html.BeginForm(FormMethod.Post))
{
<p>Search For: </p>
#Html.TextBox("companyName",Model);
<input id="button" type="submit" value="Submit" />
}
</div>
<div id="popUp">
#Html.ActionLink("Get Company List", "CreateDialog", "Company", null, new
{
#class = "openDialog",
data_dialog_id = "emailDialog",
data_dialog_title = "Get Company List"
});
</div>
but i got trouble using this code.. when i click the submit button it opens another page instead of popup. The controller code is as follows:
[HttpPost]
public ActionResult Index(Companies c)
{
Queries q1 = new Queries(c.companyName);
if (Request.IsAjaxRequest())
return PartialView("_CreateDialog", q1);
else
return View("CreateDialog", q1);
}
You could use AJAX:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
$('#popUp').html(result);
}
});
return false;
});
});
</script>
<div class="left-panel-bar">
#using (Html.BeginForm())
{
<p>Search For: </p>
#Html.TextBox("companyName", Model);
<input id="button" type="submit" value="Submit" />
}
</div>
<div id="popUp">
</div>
Now ehn the form is submitted, an AJAX request will be sent to the Index POST action and since inside you test if the request was an AJAX request it will return the _CreateDialog.cshtml partial view and insert it into the #popUp div. Also it is important to return false from the form submit handler in order to cancel the default even which is to redirect the browser away from the current page.

Resources