Return javascript to view from controller - javascript

I am returning javascript from controller to view through ajax. but it gives me failure message, my code is given below.
My controller is
public ActionResult GetJava()
{
if (Request.IsAjaxRequest())
{
return JavaScript("<script>alert(\"some message\")</script>");
}
else
{
return View();
}
}
and view is
#{
ViewBag.Title = "GetJava";
Scripts.Render("~/bundles/jquery");
}
<h2>GetJava</h2>
<div><input type="button" value="GetJava" onclick="Getjavascript()" /></div>
<script type="text/javascript">
function Getjavascript() {
$.ajax({
url: '#Url.Action("GetJava","BindingJson")',
dataType: 'applicaiton/javascript;charset=utf-8',
type: 'Get',
data: 'script',
success: function (status) { status.value },
error: function (status) { alert("failure") }
});
}
</script>
What could be the possible issue?

You can create a script with src to your action, as suggested in this answer: https://stackoverflow.com/a/6778069/4251546
var script = $('<script />', {src: '#Url.Action("GetJava","BindingJson")'});
$(document).append(script)

Related

Javascript notworking in .Net6 Partial view

this is PartialView Code:
#*This PartialView will return by return PartialView()*#
<script>
alert("OK")
</script>
<h1>test</h1>
this is IActionResult Code:
[HttpPost]
public IActionResult Test()
{
return PartialView("Test");
}
** Call ActionResult**
let Test = () => {
$.ajax({
method: 'POST',
url: "/Home/Test",
success: function(data, status, xhr) {
let itm = document.getElementById("MainPage");
itm.innerHTML = data;
}
}).done(function(res) {
}).fail(function(data, status, xhr) {
});
}
</script>
after call javascript Test() function,partialview return successfully but alert("OK") not work

How to know if Ajax Post was a success?

Current Code Example:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ActionName(ViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView(model);
}
var result = //something
if (result.Succeeded)
{
return PartialView(model);
}
AddErrors(result);
return PartialView(model);
}
Form Html
#model ViewModel
#using (Html.BeginForm("ChangePassword", "Manage", FormMethod.Post, new { #id = "Form"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
//Controls
<div class="form-group">
<input type="submit" value="Save" data-loading-text="Loading..." class="btn btn-default" />
</div>
}
JQuery code Template:
$("#Form").on('click', ".btn", function (e) {
e.preventDefault();
$.ajax({
url: "Something/ActionName",
//datatype: "text",
data: $('#Form').serialize(),
type: "POST",
success: function (data) {
$("#Form").html(data);
},
error: function (result) {
alert(result);
}
});
});
Now how can I know if an AJAX POST was a success and at the same time also returning the Partial View? Return PartialView to reset Form controls and clear error incase there were on the last post.
We can create a Json result with a var and RenderPartialView as string value. Please see MVC Return Partial View as JSON :
if (data.Result == "Success") {
alert("Data Saved");
}
$("#Form").html(data);
However, is there an easier option I am missing?

In Jquery ajax get the detail while entering in one field

I am using MVC. In my one page, if i type one value that is process, if it exists the related details will populate in other all fields. how to do this in Ajax call?
Controller:
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return View("Call",partner);
}
Call is the Aspx page.
In view:
<script type ="text/javascript">
$('#getPincode').text('Get Pincode') // Sets text for company.
.attr('href', '#');
$("#getPincode").click(function () {
$('#getPincode').text('Get Company')
.attr('href', 'GetDetail?pincode=' + $('#Pincode').val());
});
$("#Pincode").blur(function () {
$("#checkPincode").trigger('click');
});
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
But i don't know how to populate the result into my view which means editor fields???
View:
<%:Html.TextBox("Address")%>
You can try this one:
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner, JsonRequestBehavior.AllowGet);
}
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = {'pincode': name};
$.ajax({
type: "POST",
url: "/GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
return it as a jsonResult
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner);
}
or if you want to load partial view load it as
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return PartialView("Call",partner);
}
<div id="myDiv"></div>
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
$('#myDiv').html(data);
}
});
return false
});
});

ASP.NET MVC: Redirecting errors in partial to main view

I have a partial that I refresh via Ajax.
View Javascript:
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
$('#partialHolder').html(result);
}
});
}
});
Refresh action:
[HttpPost]
public ActionResult Refresh(int id)
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
This works well, except that when an error (such as an HTTP exception) occurs, the error view is sent to the partial when I want it to be shown as the main view.
Error action:
public ActionResult Error(string message)
{
ViewBag.Message = message;
return View();
}
I have tried using Javascript (both in the view and returned by the controller) to redirect the browser, however both are buggy and I assume bad practice.
Try as
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
$('#partialHolder').html(result);
},
error: function(result){
//call new action
}
});
}
});
Assuming Error() returns a complete view (with layout and script/css), you could always try completely overwriting your document:
success: function (result) {
$('#partialHolder').html(result);
},
error: function(xhr) {
if(xhr.responseText) {
var newDoc = document.open("text/html", "replace");
newDoc.write(xhr.responseText);
newDoc.close();
}
}
This will effectively overwrite your entire dom and will cause you to lose everything that was on the page.
Credits for document rewrite to this answer
Try something like this
in your action
[HttpPost]
public ActionResult Refresh(int id)
{
try
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
catch
{
return PartialView("~/Views/PartialView.cshtml", null);
}
}
so in your ajax success
if (result != null) {
//do your stuff
} else {
// the controller action returned a partial
$('#divInYourMain').html("Error 123");
}
I managed to solve this in a similar way to theLaw's answer, by using a try/catch block and the Content helper method to return a simple string which triggers a redirect.
Refresh Action:
[HttpPost]
public ActionResult Refresh(int id)
{
try
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
catch
{
return Content("error");
}
}
View Javascript:
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
if (result == "error") {
location.replace("#Url.Action("General", "Error")");
}
else {
('#partialHolder').html(result);
}
}
});
}
});

How to not able to hit the controller in my asp.net mvc application using this code

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
GOTO = function () {
alert("yes");
$.ajax({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
My Controller ActionResult is something like this
JsonResult
[HttpPost]
public System.Web.Mvc.JsonResult Index(FormCollection collection)
{
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}
I am not able to return the JsonResult here allways I am getting popupmessage saying u have choosen to open this dialogue? is there something I am doing wrong?
thanks
Try this instead -- and make sure jQuery is loaded first. Note the changes to apply the handler via jQuery instead of inline, serializing the data, generating the URL in code dynamically rather than hard-coded, and returning false from the click handler to prevent normal form submission.
<script type="text/javascript">
$(function() {
$('input[type=button]').click( function() {
var data = $('form').serialize(); // or however you get your data
$.ajax({
cache: false,
type: "POST",
url: "<%= Html.Action( "index", "home" ) %>",
data: data,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
return false; // don't do the normal submit
});
});
</script>
<input type="button" value="submit" />
you need to put the button in a form tag and call the GOTO function in onsubmit event
It looks like your data: datastring might be the problem. Check to make sure that the name of your data parameter is the same as your method parameter.
I would try to approach it more like this ...
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$(form).submit(function() {
alert("yes");
$.post({
cache: false,
type: "POST",
url: "/Home/Index/",
data: datastring,
dataType: "json",
success: function (data) {
alert("Ohh Yaa Success");
}
});
});
}
</script>
<form>
// your form fields
<input type="button" value="submit" />
</form>
</asp:Content>
And then your controller should look more like this.
Notice how we changed the parameter to a string that matches your jQuery data field.
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
// you can deserialize your Json here.
//return Content("<xml>this is just test</xml>", "text/xml");
//return Content("this is just test", "text/plain");
if (Request.AcceptTypes.Contains("application/json"))
{
return Json(new { id = 1, value = "new" });
}
else if (Request.AcceptTypes.Contains("application/xml") ||
Request.AcceptTypes.Contains("text/xml"))
{
}
if (Request.AcceptTypes.Contains("text/html"))
{
//return View();
}
return Json(new { foo = "bar", baz = "Blech" });
}

Categories