I have a button in a webgrid row defined as such:
grid.Column("Fault", header: "Fault", format: (item) =>
{
if (item.Fault != null)
{
return new HtmlString(string.Format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage({0})' value='Fault' />", item.Fault.Message));
}
return "";
}))
This is my ShowFaultMessage function:
function ShowFaultMessage(message) {
$.ajax({
url: '/Home/Message/',
data: message,
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
var w = window.open("/Home/Message", "Fault Message", "width=400, height=400");
$(w.document.body).html(result.responseText);
}
});
};
This is not working though. I know that item.Fault is correct because my If Block works in the column definition. But when I click the button, it throws an undefined reference exception. How can I make this work. I am new to MVC, but something like this is really easy with xaml. I refuse to believe it's not possible in razor/mvc.
EDIT: This is my action method for loading the popup window view:
public ActionResult Message(string faultMessage)
{
var model = new MessageViewModel { Message = faultMessage };
return View(model);
}
Also edited my other code blocks to show their current state.
Rewrite the return to be something like this
return new HtmlString(string.format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage({0})' value='Fault' />", item.Fault));
You need to use the string.format to insert the value into the string
Related
I posted this yesterday but i may not have explained my situation well.
I have 3 grids on a page that are built dynamically through JavaScript.
I then have 3 separate JavaScript methods to set a session when a row is clicked in a certain grid.
Once the session is set i would like it to navigate to the next page.
Here is what i have
OnClick event
$('#clinician-planned').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetPASession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-recent').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetRDSession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-theatre').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetTESession", "Clinician")';
AjaxCall(Location, ID);
});
AJAX Post To Controller
function AjaxCall(Location, ID) {
alert('1');
$.ajax({
type: 'POST',
url: Location,
dataType: 'text',
async: false,
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).done(function (response) {
alert('2');
location.href = "#Url.Action("Summary", "Patient")" + "/" + ID;
});
}
Here are the controller methods
public ActionResult SetPASession()
{
Session.Remove("Clinician");
Session["Clinician"] = "pa";
return Json(null);
}
public ActionResult SetRDSession()
{
Session.Remove("Clinician");
Session["Clinician"] = "rd";
return Json(null);
}
public ActionResult SetTESession()
{
Session.Remove("Clinician");
Session["Clinician"] = "te";
return Json(null);
}
The problem i have is when the row is clicked "alert('1'); shows instantly, however it seems like it takes a while and waits for all grids to be populated before the 2nd alert appears. I have tried putting async: false, but this doesnt seem to work.
Any ideas would be much appreciated.
I have a button that when you click it, it will show a confirmation box. If the user clicks 'ok', the word 'reached' would display inside of the div named 'EventData'.
So far the confirmation box shows when I click the button but 'EventData' won't show the word 'reached' when I confirm it.
*the 'event_id' has a value
I think the problem is with the url part where it won't go in the function
Route:
Route::post('/ArchiveEventPosts','AdminController#ArchiveEventposts')->name('ArchiveEventposts');
Script:
$(document).on('click', '.archive', function() {
var event_id = $(this).attr('event_id');
var x = confirm("Are you sure you want to archive this record?");
if (x) {
$.ajax({
method: "POST",
url: '{{ route("ArchiveEventposts") }}',
data: {
event_id: event_id
},
success: function(data) {
$('#EventData').html(data);
alert('Record Archived');
}
});
}
});
Function in the controller:
public function ArchiveEventposts(Request $request)
{
echo 'Reached';
}
You might need to change the way your route is assigned. What you are doing is assigning a plain string to the URL with a single quotation mark. Try like this:
var archiveEventpostsRoute = "{{ route('ArchiveEventposts') }}";
and below
url: archiveEventpostsRoute,
Also, make sure that your controller is returning the proper data, as stated in the other answer:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
Your controller method is not returning any data; it's simply printing the word "Reached".
You'll need to change the function to something like this:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
I have to perform following operation.
On a button click from View1, do Ajax request and get complex object as return.
Pass this object to View2 as parameter.
Process the data sent from view1 in client side(inside $(window).load()).
Below is my code:
View1 :
var Url = baseUrl() + "/InteractiveReport/GetRatingProfitData/";
$.ajax({
type: "POST",
url: Url,
contentType: "application/json; charset=utf-8",
dataType: "html",
// dataType: "json",
data: JSON.stringify({ "Projects": SelectedProjectinfo }),
success: function (JsonData) {
debugger;
var w = window.open('about:blank');
w.document.open();
w.document.write(JsonData);
w.document.close();
},
error: function (retVal) {
alert("error:" + retVal.responseText);
}
});
InteractiveReportController :
public ActionResult RatingProfitReport(ProfitRatingInfoModel RatingProfitData)
{
return View("RatingProfitReport", RatingProfitData);
}
public ActionResult GetRatingProfitData(IRSelectedProjectInfoModel Projects)
{
ProfitRatingInfoModel RatingProfitData = new ProfitRatingInfoModel();
//GET RatingProfitData from Database
return RatingProfitReport(RatingProfitDataMdl);
//var jsonSerializer = new JavaScriptSerializer();
//string response = jsonSerializer.Serialize(RatingProfitDataMdl);
//return Json(response, JsonRequestBehavior.AllowGet);
}
View2 :
#using Enterprise_Dashboard.Models
#model ProfitRatingInfoModel
<script>
//Control not entering this section
$(document).ready(function () {
init_bind_rating_profit_table();
});
function init_bind_rating_profit_table()
{
debugger;
var RatingProfitData = #Model.ProfitRatingData;
alert(RatingProfitData[0].BU);
}
</script>
Is there any better way to redirect to different view from Ajax call with parameters.
from my View1, if i directly make Ajax call to View2, i cannot pass complex object as parameter, since its too big string.
Is there any way i can set RatingProfitDataMdl into Session or ViewBag or ViewData or anything else and i can access it in View2?
OR
Is there any way i can eliminate Ajax call on button click so button click on View1 will automatically call GetRatingProfitData and it internally redirects to RatingProfitReport with modal object parameter?
OR
Completely different approach available to handle this scenario?
I have an HTML able, which I bind by using the following Action in MVC controller:
public ActionResult BindTable(int ? page)
{
int pageSize = 4;
int pageNumber = 0;
List<Users> _users = query.ToList();
return View(_users.ToPagedList(pageNumber, pageSize));
}
Below the table I have the following HTML:
<textarea class="form-control" style="resize:none;" rows="9" placeholder="Enter value here..." id="txtValue"></textarea>
<br />
<button style="float:right; width:100px;" type="button" onclick="CallFunction()" class="btn btn-primary">Update specific record</button>
The Javascript function responsible for calling the action is as following:
function CallFunction() {
if ($('#txtValue').val() !== '') {
$.ajax({
url: '/User/UpdateUser',
type: 'POST',
data: { txt: $('#txtValue').val() },
success: function (data) {
$('#txtValue').val('');
alert('User updated!');
},
error: function (error) {
alert('Error: ' + error);
}
});
}
And here is the Action responsible for updating the user:
public ActionResult UpdateUser(string txtValue)
{
var obj = db.Odsutnost.Find(Convert.ToInt32(1));
if(obj!=null)
{
obj.Text= txtValue;
obj.Changed = true;
db.SaveChanges();
return RedirectToAction("BindTable");
}
return RedirectToAction("BindTable");
}
Everything works fine. But the table doesn't updates once the changes have been made ( it doesn't binds ?? )...
Can someone help me with this ???
P.S. It binds if I refresh the website.. But I want it to bind without refreshing the website...
I created a BIND function with Javascript, but it still doesn't binds:
function Bind() {
$(document).ready(function () {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
});
}
You're not actually updating the page after receiving the AJAX response. This is your success function:
function (data) {
$('#txtValue').val('');
alert('User updated!');
}
So you empty an input and show an alert, but nowhere do you modify the table in any way.
Given that the ActionResult being returned is a redirect, JavaScript is likely to quietly ignore that. If you return data, you can write JavaScript to update the HTML with the new data. Or if you return a partial view (or even a page from which you can select specific content) then you can replace the table with the updated content from the server.
But basically you have to do something to update the content on the page.
In response to your edit:
You create a function:
function Bind() {
//...
}
But you don't call it anywhere. Maybe you mean to call it in the success callback?:
function (data) {
$('#txtValue').val('');
Bind();
alert('User updated!');
}
Additionally, however, that function doesn't actually do anything. For starters, all it does is set a document ready handler:
$(document).ready(function () {
//...
});
But the document is already loaded. That ready event isn't going to fire again. So perhaps you meant to just run the code immediately instead of at that event?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
}
But even then, you're still back to the original problem... You don't do anything with the response. This AJAX call doesn't even have a success callback, so nothing happens when it finishes. I guess you meant to add one?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do something with the response here
}
});
}
What you do with the response is up to you. For example, if the response is a completely new HTML table then you can replace the existing one with the new one:
$('#someParentElement').html(data);
Though since you're not passing any data or doing anything more than a simple GET request, you might as well simplify the whole thing to just a call to .load(). Something like this:
$('#someParentElement').load('/User/BindTable');
(Basically just use this inside of your first success callback, so you don't need that whole Bind() function at all.)
That encapsulates the entire GET request of the second AJAX call you're making, as well as replaces the target element with the response from that request. (With the added benefit that if the request contains more markup than you want to use in that element, you can add jQuery selectors directly to the call to .load() to filter down to just what you want.)
I may be missing something obvious here, but how could I rewrite this code!
i am trying here to store the value entered in the textbox(Textbox was showed in javascript dialog page).In a javascript dialog page i have one 'ok' button.. when i click the button i want to store the value entered in the textbox.I want to save the content using Ajax.
Please see my sample code
View page:
<script language="javascript" type="text/javascript">
$(function () {
$('.button').live('click', function () {
$('.Text_dialog').dialog('open');
});
$('.Text_dialog').dialog({
autoOpen: false,
buttons: {
'Ok': function () {
var textValue = $(':txtValue').val();
$.ajax({
url: '/Home/About',
type: 'POST',
data: { str: textValue },
success: function (result) {
alert(result.val);
}
});
},
}
});
});
</script>
<input type="button" value="Add Value" class="button" />
<div class="Text_dialog" title="Basic modal dialog">
TextValue: <input type="text" class="txtValue" />
</div>
Control page:
[HttpPost]
public ActionResult About(string str)
{
ValidateClass ObjAM = new ValidateClass();
int value = ObjAM.ValidatetextValue(str);
return Json(new { val = value });
}
Model page:
public class ValidateClass
{
DataClasses1DataContext dbObj = new DataClasses1DataContext();
public int ValidatetextValue(string str)
{
string value = (from SearchtextValue in dbObj.Options
where SearchtextValue.OptionName == str
select SearchtextValue.OptionName).Single();
if (value == null)
{
return 1;
}
return 0;
}
}
When i run this code i am getting script error like "Object doesn't support this property or method".Please advice
Change data: { str: textValue } to data: "{ 'str' :'" + textValue +"' }"
If you are confused on escaping the quotes properly, try this.
$(function() {
$('.button').live('click', function() {
$('.Text_dialog').dialog('open');
});
$('.Text_dialog').dialog({
autoOpen: false,
buttons: {
'Ok': function() {
var DTO = "{ 'str' :'" + $('.txtValue').val() +"' }";
$.ajax({
url: '/Home/About',
type: 'POST',
data: DTO,
success: function(result) {
alert(result.val);
}
});
},
}
});
});
Please note that I have changed the :txtValue to .txtValue as it is the correct selector.
can you try changing
<input type="text" class="txtValue" />
to
<input type="text" class="txtValue" id="txtValue" />
and
var textValue = $(':txtValue').val();
to
var textValue = $('#txtValue').val();
I've never used : selector... but I think it will return you a collection and you should use index [0] or, why don't you use class selector .?
Edit: as I see you cannot use : in this case
also you can add dataType: "json",into your Ajax request, and change your method return type from
public ActionResult About(string str)
to
public JsonResult About(string str)
EDIT 2:
have you included the library where dialog() function is? after including the jquery library?