Rendering an html string to view - c#

I have two controller actions that target the same view. That is, I have specified a view name on the call to View from controller action. The second action puts an html string in a ViewBag. I simply just want to display this html string in the view. I have tried
#ViewBag.HtmlDoc
and
#Html.Raw(ViewBag.HtmlDoc)
but nothing is rendered.
Any help would be appreciated. Thanks in advance.
--controller code---
public ActionResult ShowReport(string URL)
{
string tableString = "";
[Code to Create table called ReportTable and add rows etc]
tableString = RenderControlToString(ReportTable );
ViewBag.Table= tableString;
return View("ShowReport");
}
I debugged the ViewBag.Table on the View and can see the html string. But the View never gets updated / rendered. I tested with a simple text like:
#if (ViewBag.Table != null)
{
//#ViewBag.Table;
#:The day is: #DateTime.Now.DayOfWeek.
}
It goes into the code so I know ViewBag.Table is not null, but the string doesn't get rendered, either.
Do I need to refresh RenderBody() in the _layout.cshtml??? or something to that effect?
-- ajax call--
a button onclick event calls this ajax method:
$.ajax({
url: "/Home/ShowReport",
data: { URL: urlString} ,
type: 'POST',
success: function(data) {
alert(data);
},
error: function (e, textStatus, jqXHR) {
alert(e.statusText);
}
});

Change your action method to return JSON content
public ActionResult ShowReport(string URL)
{
string tableString = "";
[Code to Create table called ReportTable and add rows etc]
tableString = RenderControlToString(ReportTable );
//ViewBag.Table= tableString;
return this.Content(tableString, "application/json");
}
alter your JQuery to reutilize your return value
success: function(data) {
$('#divTable').innerHTML(data);
and add a div to your view where you want to render the html
<div id='divTable'></div>

Related

Using Action in Controller every 10min [duplicate]

I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;

How to trigger controller and open new page (along with model) with ajax

I have a link. Its triggers my ajax. I want to open a new page after this triger.
But it's returning back to my ajax after the trigger. There is my code.
HTML
<a onclick="SiparisYazdir(#item.id)" >Print</a>
ajax
function SiparisYazdir(id)
{
$.ajax({
url: '/Order/Print',
type: 'GET',
data: { "value": value, 'id': id } // value is taking from another method.
});
}
controller
public IActionResult Print(int value, int id)
{
//taking model here
return View(model);
}
return View(model) will return the html content of your view
you cant put this html into your desired tag
function SiparisYazdir(id)
{
$.ajax({
url: '/Order/Print',
type: 'GET',
data: { "value": value, 'id': id } // value is taking from another method.,
success:(result)=>{
$('your_desire_elemnt').html(result)
}
});
}
If you want to redirect to another page, I think there is no need ajax here
function SiparisYazdir(id) {
window.location.href = "/Home/Privacy?value=" + value + "&id=" + id;
}

Jquery .post method is sending a null value. How to pass actual value to controller?

I have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty

How to pass a JavaScript Array to ASP.Net MVC Action as part of post

I have a cshtml as follow,
DoPost.cshtml
#using (Html.BeginForm("Purchase", "PurchaseOrder", FormMethod.Post, new { #id = "frmPurchase" }))
{
// statements
// statements
<input type="button" id="submitPurchase" onclick = "myPurchase()" value="Select" />
}
In Javascript I have an array strings in variable "ExtraItems"
ExtraItems[0] ="123"
ExtraItems[1] ="124"
ExtraItems[2] ="125"
My Action which accept the data is as follows,
public ActionResult Purchase(PurchaseOrderModel model)
{
//Do some stuff with the passed data
return View("Purchase", model);
}
In the above PurchaseOrderModel, I have the property
public string[] SelectedProducts { get; set; }
to accept the Javascript Array elements.
What I tried:
The simple post did not work as the JavaScript array elements are not part of the Form elements,I couldn't use a #Html.HiddenFor because it is an array.
Hence tried to do an Ajax post under function myPurchase(),
$a.post('#Url.Action("Purchase", "PurchaseOrder")', { SelectedProducts: ExtraItems });
Here I did not get the ExtraItems details under model.SelectedProducts in the action. The biggest issue was i wanted to load the Purchase.cshtml View from the action, instead I got the controll back to the Jquery Post.
Please help me how can I solve this.
You should post your javascript array as a json object. You use the JSON.stringify() method converts a value to JSON. Something like :
$.ajax({
url: '#Url.Action("Purchase", "PurchaseOrder")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
SelectedProducts: ExtraItems
})
});
Here is my example for solving your issue
-----------------------------------------
//Script
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script>
var ExtraItems = ["aa","bb","cc","ff"];
function a()
{
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
alert( 'Sucs' );
}
} );
}
</script>
<button onclick="a();">click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
//Controller
[HttpPost]
public ActionResult Index( string[] SelectedProducts )
{
return View();
}
Take a string property in your model and then send the data as comma separated string
var dataToSent = ExtraItems.join(',')
If you have a property named Datum of type string in your model Purchase then the data to be sent will be, passing model
data : 'Datum=' + dataToSent
In your action you can split data into array
also for return response you have to redirect the page in the success function of your ajax call
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
window.location.href = "/controller/action" <--your url
}
} );
Use $.ajax function with the option traditional:true for enabling ASP.NET MVC default model binding for the list of string items.

Text of the anchor tag passed to the controller

Is it possible to get the text of the anchor tag passed to the controller?
Student Information
This is in the view.
When I click the link, I want to use "Student Information" (the inner text) in the controller.
How can I get it programmatically? (No Hard coding)
I am using C#.
Thanks in Advance.
You can pass it as routeValues.
In your view:
Student Information
In your controller:
public ActionResult SearchStudent(string innerText)
{
// Do your thing.
return View();
}
I have an example if you really want to send inner text to controller
give id to your tag like this
<a id="linkData">Student Information</a>
in jQuery add this
$('#linkData').click(function () {
var dataLink = $('#linkData').text();
$.ajax({
type: "POST", data: { data: dataLink }, url: "#Url.Action("SearchStudent","Home")", success: function (result)
{
alert(result);
}
});
});
In your controller add an argument like this
public ActionResult SearchStudent(string data)
{
return Json(data, JsonRequestBehavior.AllowGet);
}
It will return data to function(result) and alert(result) to show your inner text.
Hope you understand me. I'm not good in English.

Categories