Javascript doesn't work after calling changePage() in my example. Everything is fine after first request page, but when I try to select other items, changePage() doesn't work. 'pageshow' event didn't help me. What's wrong with me?
My simple example:
#model TestMobileSearch.Models.ListModelView
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
$(document).delegate("#main", "pageinit", function () {
$("#filterCategory").bind('change', function () {
$.mobile.changePage(this.value);
});
});
</script>
Category Name: #Model.CurrentName
<select id="filterCategory" data-theme="c" data-corners="false">
#foreach (var item in Model.Names)
{
<option value="#Url.Action("List", "Cat", new {name = item})">#item</option>
}
</select>
I use jquery.mobile-1.3.1.js
Thanks
Why don't you delegate directly the #filtercategory change event?
$(document).delegate("#filterCategory", "change", function () {
$.mobile.changePage(this.value);
});
By the way, delegate is deprecated. If you use a newer jQuery, use on instead.
Related
I need the value from the option to be assigned to my model once the user clicks on the specific option.
<select name="isEmailVerified" class="form-select">
<option value="" selected> all </option>
<option value="true"> verified </option>
<option value="false"> unverified </option>
</select>
expected value => #Model.IsEmailVerified.XXXXX(my value)
What I usually do when I want to asyncronously send data back and forth is this:
I take advantage of Tag Helpers as they're great and saves you a ton of boilerplate code, so I create a standard <form> element without an actual Submit button, just a div that looks like one. You might want to check official MSDN Documentation for the Select Tag Helper to create an appropriate model.
#model VerificationModel
<form asp-action="CheckEmail" method="post">
<select asp-for="IsEmailVerified" asp-items="Model.VerificationTypes">
<div id="SubmitCheck" class="btn">Check email</div>
</form>
Create a javascript function that takes care of the actual submitting chore. Since the form is created with the Tag Helpers, the request body will automatically bind
$('#SubmitCheck').on('click', function() {
let form = $(this).parents('form')[0];
let formData = new FormData(form);
let request = function () {
return fetch(form.getAttribute('action'), {
method: 'POST',
body: formData
});
};
let onresponse = function() {
// do some preliminary actions on 200 response
}
let callback = function() {
// deal with response result
}
let onerror = function() {
// deal with errors
}
request()
.then(response => onresponse())
.then(result => callback())
.fail(err => onerror());
})
Add the [FromForm] attribute to Controller props (model is the same used in the page) to ensure model binding
public async Task<CustomResultClass> CheckEmail([FromForm] VerificationModel model)
{
// do something
}
I'm facing an issue when livewire DOM update jquery plugin not work , jquery plugins breaks and not working . Kindly proper guid thanks
When select2, I solved the issue by doing the next
//in component
public $selectedElem;
public function hydrate()
{
$this->emit('select2Hydrate');
}
public function updatedSelectedElem($value)
{
dd($value);
}
//in blade
<select class="form-control select2_livewire" wire:model="selectedElem">
//.....
</select>
<script>
$(document).ready(function() {
window.loadSelect2 = () => {
$('.select2_livewire').select2().on('change',function () {
#this.set('selectedElem',$(this).val());
});
}
loadSelect2();
window.livewire.on('select2Hydrate',()=>{
loadSelect2();
});
}
</script>
I have a few viewmodels, which contains a few functions like:
public override string ToString()
{
return $"{M_IV_ID} {M_IV_INVOICEAMOUNT} {M_IV_MANDANT} {M_IV_TOTALAMOUNT} {M_IV_VEHICLE_PURCHASE} {M_IV_URGENT}";
}
And update / insert functionalities. All of them work. I wrote them separately from my Asp.NET project and tested them since I wanted to do my back end first.
Now I tried to use those functions in my Asp.NET application:
First I get Data from the db in my Controller:
M_IV_INVOICE invoice = QueryBuilder.GetFirstOrDefault(new M_IV_INVOICE(), #"WHERE M_IV_ID IN (75693)");
And pass it to my view:
public ActionResult Index()
{
return View(invoice);
}
Now I tried to use my toString() method just to see if it works:
<form id="formUpdate" runat="server">
<div>
<asp:button id="Button" class="btn btn-primary" runat="server">Update</asp:button>
</div>
</form>
#{
string MyFunction()
{
return Model.ToString();
}
}
#section Scripts
{
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
var button = document.getElementById('Button');
button.addEventListener('click', function () {
var test = "#MyFunction()";
console.log(test);
});
});
</script>
}
And if I do this, it works, and I get my model values printed in the browser console.
If I try to use my Update function instead of the toString() method:
public bool Update()
{
using (IDbConnection conn = ConnectionManager.GetConnection())
{
try
{
conn.Query(QueryBuilder.BuildUpdateForEntity(this, string.Format(" WHERE {0} = {1}", GetKey().Item1, GetKey().Item2)));
return true;
}catch(Exception e)
{
// TODO: Exceptionhandling
}
}
return false;
}
I get a Ora Exception right when the page loads, no button click performed:
Oracle.DataAccess.Client.OracleException: ORA-00936: missing expression
I struggle with understanding why, though.
The select I perform in my controller to get the data in the first place is working just fine, and as I said, if I print my model on button click, it works too.
What am I missing?
Edit:
It seems like the function is directly called while the eventhandler is added and since it has no data at the time, the ORA error is occurring.
But why? I don't understand this behavior.
Another Edit:
It has indeed something to do with the model isn't ready or something:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function () {
var button = document.getElementById('Button');
button.addEventListener('click', function () {
setTimeout(() => { console.log("#MyFunction()") }, 3000);
});
});
</script>
I added the delay and no error on loading the page.
But that would be just a band aid, not a solution.
If someone has an idea how to prevent that behavior, I would appreciate it.
The #{}symbol is used to write server-side C# or VB code with HTML code, so in the javascript, when you use the #MyFunction() function, the Myfunction will execute. You could set a break point in the MyFunction and the button click event to check it, no matter using the ToString() method or the Update() method, they will work when the DOMContent Loaded. So, when use the Update() method, you will meet the missing expression error.
Based on your description, you want to do some action (call the server-side function/method) when user clicks the button, right? If that is the case, I suggest in the controller you can add the Myfunction and Update action methods, then, in the button click event, you can use JQuery get(), post() or Ajax method to call the action method, refer the following code:
Controller:
[HttpPost]
public JsonResult AjaxMethod(string name)
{
PersonModel person = new PersonModel
{
Name = name,
DateTime = DateTime.Now.ToString()
};
return Json(person);
}
and View Page:
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
#section Scripts{
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Test/AjaxMethod",
data: { name: $("#txtName").val() },
success: function (response) {
alert("Hello: " + response.name + " .\nCurrent Date and Time: " + response.dateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
}
Do we have better ways to handle it?
#foreach (var item in Model)
{
<div id="divDetail#{#item.CategoryId}"/>
#Ajax.ActionLink(
item.CategoryName,
"GetDetails",
new { id = item.CategoryId },
new AjaxOptions() { UpdateTargetId = string.Format("divDetail{0}", item.CategoryId) })
}
</div>
}
I would use the HTML.ActionLink helper method to generate the link and then use my custom jQuery ajax call to get the data. The advantage of doing this is i have full control so that i can do some manipulation of the response data before showing in the detail div.
I added a CSS class to the link so that i can be more specific (in selection of element) when binding my functionality.
#foreach (var item in Model)
{
<div id='divDetail#(item.ID)'></div>
#Html.ActionLink(item.CategoryName, "GetDetails", new { #id = item.CategoryId}, new {#id= "link-"+item.CategoryId, #class="lnkItem" })
}
and the script is
<script type="text/javascript">
$(function () {
$(".lnkItem").click(function (e) {
e.preventDefault();
var itemId = $(this).attr("id").split("-")[1]
$.get($(this).attr("href"), { id: itemId }, function (data) {
//i am free to do anything here before showing the data !
$("#divDetail" + itemId).html(data);
})
});
});
</script>
I have a Partial View with two opposite ActionLinks inside:
<div id="divStatus>
#if (IsAuthenticated)
Html.ActionLink("Say Bye", "ProcBye", "Account")
else
Html.ActionLink("Say Hi", "ProcHi", "Account")
</div>
Each Action link calls a different method on the Controller.
I hear I should use Ajax.BeginForm but I'm still NOT clear how to put this?
My understanding is that I need a <div id="divStatus"> to display the result, but in my case ...the result is the Partial View itself.
QUESTION: How do I ensure make it so the Controller just refreshes the calling Partial View??
Shall I just add a div outside the PV?
Shall I add the div inside the PV surrounding the '#if (IsAuthenticate)' call?
Is it better to use Ajax.BeginForm or Ajax.ActionLink in this case?
CODE: What should the code for the Controller look like?
public ActionResult ProcBye()
{
// do something on the server
// set IsAuthenticated = false;
return PartialView("_myPV");
}
There is NO Validation Involved, NO "external" div that needs to be populated, just a simple refresh of the PV independently from what page the PV is located.
Any help will be truly appreciated !!!
Personally I wouldn't use neither. I would use a separate javascript file in which I would AJAXify the link:
$(function() {
$('.mylink').click(function() {
$('#resultdiv').load(this.href);
return false;
});
});
where resultdiv will be a div which will be update with the partial result returned from the controller action:
<div id="resultdiv"></div>
You just need to put the mylink class:
#if (IsAuthenticated)
{
#Html.ActionLink("Say Bye", "ProcBye", "Account", null, new { #class = "mylink" })
}
else
{
#Html.ActionLink("Say Hi", "ProcHi", "Account", null, new { #class = "mylink" })
}
You could also use Ajax.ActionLink if you wanted to:
#if (IsAuthenticated)
{
#Ajax.ActionLink("Say Bye", "ProcBye", "Account", new AjaxOptions { UpdateTargetId = "resultdiv" })
}
else
{
#Ajax.ActionLink("Say Hi", "ProcHi", "Account", new AjaxOptions { UpdateTargetId = "resultdiv" })
}
Just don't forget to include the jquery unobtrusive ajax script in this case:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>