I am trying to call a window.onload function inside a cshtml view.
My code looks like this.
#model BusinessModel
#if(Model.Business != null)
{
<script>
window.onload = function () {
if ('#Model.Business'!='') {
var data = {
//JSON Object
};
$.ajax({
url: www.google.com,
method: 'POST',
headers:{},
data : JSON.stringify(data),
success: function (response){
window.location.replace(new url);
}
});
return false;
}
}
</script>
} else {
// Some basic HTML code
}
When i am trying to do something like this, when the condition matches it is never hitting the window.onload function.
Am i doing something wrong or Does this need to be handled in a different way?
Please help me with this
Thanks.
You can try to check if Model.Business is null in js.Here is a demo:
Model:
public class BusinessModel
{
public List<Business> Business { get; set; }
}
Action:
public IActionResult Test1()
{
var model = new BusinessModel { Business = new List<Business>() };
return View(model);
}
View:
#model BusinessModel
#if (Model.Business == null)
{
<h1>null</h1>
// Some basic HTML code
}
<script>
window.onload = function () {
if ('#Model.Business'!='') {
alert("Hello");
}
}
</script>
result:
Related
I'm getting an error that my Action Method was not found, but can't figure out what's wrong. I searched the internet now for hours but haven't found a solution till now.
In my View I have a JavaScript function:
<script type="text/javascript">
function ShowHideAds(button) {
var dAds = document.getElementById("dAds");
if (dAds.style.display == "none") {
dAds.style.display = "block"
var txtBox = "Visible";
$.post('#Html.Action("GetState","Rights")', { txtAds: txtBox });
}
else {
dAds.style.display = "none"
var txtBox = "Hidden";
$.post('#Html.Action("GetState", "Rights")', { txtAds: txtBox });
}
} </script>
I'm switching between a Textbox and a Listbox and depending on which is visible, I want to pass the parameter to my method.
My method in my Controller is the following:
[HttpPost, ActionName("GetState")]
public ActionResult GetState(string txtAds, string txtRg)
{
if (txtAds != null)
stateTxtAds = txtAds;
if (txtRg != null)
stateTxtRg = txtRg;
return View();
}
and finally here is my routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Before using the #Html.Action() method I had following line of code:
$.post("/Rights/GetState", { txtAds: txtBox });
but this did not work when the project was deployed so I tried to use the #Html.Action two send my variables to my controller method.
Can anyone help please?
Thank you!
GetState(string txtAds, string txtRg) has two parameters but you are only providing one. If you want it to accept two but only provide it one like you are doing in the call, do the following.
For example for the post #Html.Action("GetState", "Rights")', { txtAds: txtBox }:
GetState(string txtAds, string txtRg = "")
This way you can just send txtAds if you want and it should reach it.
The ajax I would recommend:
var json = '{txtAds: "' + txtAds + '"}'
$.ajax({
url:'#Url.Action("GetState", "Rights")',
type:'POST',
data: json,
contentType: 'Application/json',
success: function(result){
// Whatever you want to do next.
}
})
I have a simple controller like this:
public JsonResult GetPosts(int? id)
{
var varid = id;
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
NeighbourhoodId = varid,
Message = post.Message,
PostedByName = post.ApplicationUser.UserName,
PostedDate = post.PostedDate.ToString(),
PostId = post.PostId,
});
return Json(ret, JsonRequestBehavior.AllowGet);
}
Here, i am able to get the dropdown selected value.I am assigning it to a variable varid and then assigning it to NeighbourhoodId.
But, when the view page is rendered nothing changes all the 4 Post are showing.but in reality it should display only 2 Post.
This is my view page code:
<ul id="msgHolder" data-bind="foreach: posts">
<li class="postHolder">
<p><a data-bind="text: PostedByName"></a>: <span data-bind=" html: Message"></span></p>
and my wallpost.js file in script folder where all knockout view model related code is here.It first loads all the Post from database correctly but data doesnot get filtered if i am trying to filter it with dropdown change.
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.NeighbourhoodId = data.NeighbourhoodId;
self.Message = ko.observable(data.Message || "");
self.PostedByName = data.PostedByName || "";
self.PostedDate = getTimeAgo(data.PostedDate);
self.error = ko.observable();
function viewModel() {
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
self.loadPosts = function () {
// to load existing posts
$.ajax({
url: postApiUrl,
datatype: "json",
contentType: "application/json",
cache: false,
type: 'Get'
})
.done(function (data) {
var mappedPosts = $.map(data, function (item)
{ return new Post(item); });
self.posts(mappedPosts);
})
.fail(function () {
error('unable to load posts');
});
}
return self;
};
ko.applyBindings(new viewModel());
and my dropdown related code is here:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList,"Select a Location")
<script type="text/javascript">
$(document).ready(function () {
$("#Locations").change(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("GetPosts", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
When i debug, i am getting correct id value in controller but there is problem in filtering out data. Is there a need for some change in knockout file.what to do here ??
Instead of mixing jquery event handlers and knockout bindings, i think it's better for you handle all with knockout.
Bind your select element (drop down) with the options binding and load the locations array on view model initialization; bind the value to a observable property, ex: 'CurrentLocation'
Subscribe to the change of the property 'CurrentLocation', ex:
myViewModel.CurrentLocation.subscribe(function(newValue) {
//request to GetPosts here
});
On .done() function of the GetPosts request update the observableArray with the items received by the server
Hope this helps!
UPDATE
The following is a very simple example, i changed my mind and used "event" binding to handle the change event instead of "options" binding but the concept it's the same.
#Html.DropDownList("Locations", new SelectList(Model.Locations, "Id", "Name"), new { data_bind = "event: { change: reloadPosts}" })
<ul data-bind="foreach: posts">
<li data-bind="text:CompleteText"></li>
</ul>
<script>
function Post(data) {
var self = this;
self.Id = ko.observable(data.Id);
self.LocationId = ko.observable(data.LocationId);
self.Text = ko.observable(data.Text);
self.CompleteText = ko.computed(function () {
return self.Id() + " " + self.Text();
});
}
function PageViewModel() {
var self = this;
self.posts = ko.observableArray();
self.reloadPosts = function () {
$.ajax({
type:"POST",
url: "GetPosts",
data: { locationId: $("#Locations").val() }
}).done(function (data) {
var mappedPosts = $.map(data, function (item)
{ return new Post(item); });
self.posts(mappedPosts);
});
}
}
var vm = new PageViewModel();
ko.applyBindings(vm);
</script>
The GetPosts method in the controller:
[HttpPost]
public JsonResult GetPosts(string locationId)
{
var selectedPosts = posts.Where(x => x.LocationId == locationId);
return Json(selectedPosts, JsonRequestBehavior.AllowGet);
}
The posts collection in the controller in the example above it's just an inmemory collection, probably you will read it from a DB or something like that.
The post class on the c# code:
class Post
{
public string Id { get; set; }
public string LocationId { get; set; }
public string Text { get; set; }
}
And finally the viewmodel used:
public class TestViewModel
{
public List<Location> Locations { get; set; }
}
I created a small function to test Zend-Ajax interaction.
In my view I set following code
<script type="text/javascript">
var urlform = '<?php echo $this->url('inbox/default', array('controller'=>'messages', 'action'=>'addmessage')); ?>';
</script>
<div onclick="ajaxtest();">Click</div>
Then, I created following function within file custom.js, already associated to the layout
function ajaxtest() {
$.post(urlform, null, function(data) {
if (data.success) {
alert('Ok');
} else {
alert('Failed');
}
}, 'json');
}
And finally, this is the code of my addMessageAction
public function addMessageAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$response->setContent(\Zend\Json\Json::encode(array('success'=>1)));
return $response;
}
When I click on the div associated to the javascript function, nothing happens, no alert is displayed.
Where am I wrong? Does it depend on particular zend settings?
I solved the problem by ridefining function in the following way:
var ajaxpost = $.post(urlform2).fail(function() {
alert("Failed");
})
ajaxpost.done(function(data) {
var parsed = jQuery.parseJSON(data);
if (parsed.success == 1) {
alert('Ok');
}
});
I have following Jquery code the code is sending data to controller fine and now I want to redirect from here after success how can I achieve this
$('#reply_admin').click(function () {
var recipName = $('.input_eply').val();
var id =#Model.id
$.post('/Admincontact/Replt/' + id,
{ reply: recipName },
function (data) {
$('#reply').append(data);
window.location.href = '#Url.Action("Index", "Admincontact")';
});
});
and my controller is
[HttpPost]
public ActionResult Replt(string reply,string id)
{
EmailManager.admin_reply(db.contactUs.Find(Convert.ToInt32(id)).Email, reply);
return new EmptyResult();
}
Whats the meaning of
$('#reply').append(data);
If you are returning EmptyResult()
Try only
function (data) {
window.location.href = '#Url.Action("Index", "Admincontact")';
}
Javascript Code:
<script type="text/javascript">
function MusteriBilgileriKaydet2() {
var veri = {
AnaOzelDurumId: AnaOzelDurumId.GetValue(),
AnaİlgiliPersonelId: AnaİlgiliPersonelId.GetValue(),
};
if (veri.MusteriAdiTextBox1.trim() == "" || veri.MusteriAdiTextBox1 == undefined || veri.MusteriAdiTextBox1 == null) {
$("#showwarning222").html('<img src="/Image/warning.png" title="Müşteri Adı Giriniz!">').show();
}
else {
LoadingPanel.Show();
$.ajax({
url: "/Home/GenelMusterilerGridView2",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) { // Error
LoadingPanel.Hide();
alert("Müşteri Adı Mevcut");
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
else { // Success
$("#MusterilerGetir").html(mydata);
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
},
error: function () {
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
});
return false;
}
}
</script>
My Controller:
public ActionResult GenelMusterilerGridView2(MyModel model)
{
var stringView = RenderRazorViewToString("MerkezPartial", ModelleriGetir());
return Json(stringView, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { error6 = true, JsonRequestBehavior.AllowGet });
}
}
return null;
}
My all codes works well .
I only want to open in new tab page .
So
How can i open in new tab in browser after i post data to my controller ?
Any help will be greatly appreciated.
Thanks.
you can add to your html <a href tag a target that looks like this.
Link name or text
OR you can in your javascript code add
function OpenNewTab(url){
var something = window.open(url, '_blank');
something.focus();
}
Now this should be working fine but just because some clients prevent pop-ups then you could add this to your html tag too.
<div onClick="OpenNewTab();">your link name</div>
Hope this will work for you
Cheers!