Unable to send back data to action in MVC controller from javascript - c#

I use jquery to load rows into a table. Each row contains an Id.
row = '<tr><td><button type="button" class="edit-form btn btn-default" data-form-id="' + value[0].id + '"></button></td></tr>';
tbody.append(row);
On click of a button, I need this Id to be sent back to an action in the controller, which would then redirect to a new view with this Id. On the new page, I would use this Id in a javascript function, which would then load details pertaining to this id using jQuery ajax.
I am not able to acheive this. I tried several things
Tried creating html action link using javascript which did not work
Used ajax to send data(id) to the action, but the action ended up returning the html of the new view as the response instead of redirecting
I've gone through several other Stackoverflow question related to this and have tried all of them. Nothing seems to work. Please suggest how i should tackle this problem. Any suggestions would be appreciated. I have sent data to other actions in the controller, but now my problem is that, I need this Id to go to the action and it should redirect me to a new page with this info available on that page
I have pasted the Code Below for the things I have tried.
$.each(this.data, function (key, value) {
var row = '<button type="button" class="edit-form btn btn-default" data-form-id="' + value[0].id + '"><span class="glyphicon glyphicon-eye-open"></span></button></td></tr>';
tbody.append(row);
});
On click of this button I call the following code in my javascript
openEditForm: function (evt) {
var formId = $(evt.currentTarget).data("formId");
$.ajax({
url: '/Home/Test',
type: "POST",
dataType: "json",
data: JSON.stringify({ formId: formId }),
contentType: "application/json; charset=utf-8;",
success: function (response) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
In my Controller I have an action named Test which does the following
public ActionResult Test(string formId)
{
ViewBag.Title = "Testing Page ";
ViewBag.Message = "Testing Page" + formId + "hi";
return View();
}
What I want is that the action receive this formId and redirect it to a view called Test.cshtml. I need that view to have the formId info in it, so that I can use javascript on that page to make ajax calls to retreive the form info.

Used ajax to send data(id) to the action, but the action ended up returning the html of
the new view as the response instead of redirecting
By Above Line You Mean to Say that You want Data to Be posted to action ,and Action1 will call another Action where it will use That Returned ID...
So if this is The Case then Why are You using Ajax?
function myfunction()
{
var formId = $(evt.currentTarget).data("formId");
// window.location = "ActionNameHere?formId" + formId;
// foryour Case
window.location="Test?formId="+formId;
}
The Above code will Redirect you to
public ActionResult Test(string formId)
{
ViewBag.Title = "Testing Page ";
ViewBag.Message = "Testing Page" + formId + "hi";
return View();
}
From here you will have your New Page with Id in it...
The best way to initiate an HTTP request is with
document.loacation.href.replace('URL')

I would do:
option a) create a form element with an hidden field, populate it when the user clicks on the button and then submit the form to your action
<form method="post" action="/yourController/yourAction" id="frmAction">
<input type="hidden" name="parameterYouExpectinYourAction" value="" id="hdnField" />
</form>
<script>
$(".btn").on("click", function() {
$("#hdnField").val($(this).data("form-id"));
$("#frmAction").submit();
});
</script>
option b) create a normal link instead of a button like
'<a href="/controller/youraction?yourParam=' + value[0].id + '" >link</a>'
Is not the cleanest way, but could help you to make it work of figure out how to get it done in other ways (I hope).

The simplest way I see is simply an event on your button with a redirect to the URL with the ID.
$('button').on('click', function () {
window.location = 'http://yourURL' + '/' + $(this).attr('data-form-id');
});
Just modify it following your needs of course (Html.Action(...), $.post(...), ...).
Once inside your controller you can use return RedirectToAction(...) combined with the ID submitted to redirect the user to your second view.

Related

MVC button onClick

I am making my MVC application. How do I create a button in my view that a click on it will run a function from controller. I would also like to pass data from the view that the button is in. But I do not want to open a different view. I just want to run a function - Button "save to file" would save the table from the view into a file - would open a Directory browser and save a file on a disk.
This will be done with the help of ajax request from your view. You need to add a simple button on your view and call a jquery function on its onclick event like this:
<input type="button" value="save to file" onclick="saveToFile()" />
Then you can create saveToFile function to send ajax request like this: here you can create your data as per your need of fields you want to post to controller. I just adding firstField and secondField for demo:
<script type="text/javascript">
var data = { "firstField" : "value1", "secondField": "value2" };
function saveToFile() {
$.ajax({
url: "/ControllerName/ActionName",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
},
error: function (xhr) {
console.log(xhr);
}
});
});
</script>
Your action method will be like this:
[HttpPost]
public ActionResult UseShippingAddress(string firstField, string secondField)
{
//write your logic here to save the file on a disc
return Json("1");
}
Apparently, the correct solution was to use
#Html.ActionLink("weekly - PDF", "GenerateTable", "Account", new { group_id = Model.group_id, class_id = Model.class_id, type = 1 }, null)
And in GenerateTable method just return a proper file.

Linkbutton equivalent in MVC C# Razor

I am converting a web form to MVC C# razor project. I like to know how I will get the same functionality in Razor where it will create a link and sumbit the form into the same page. The web form code is -
<asp:LinkButton ID="lnkBtn_1" runat="server" Text='<%#Eval("Sales") %>' OnCommand="LinkButton1_Command" CommandArgument='<%#Eval("Sales") %>' ></asp:LinkButton>
Thanks in advance
Try this
#Html.ActionLink("buttonText", "ControllerAction", "YourController ",
new { #sales = YourModel.Parameter}, new { #class =yourcssclass" })
Your Controller
public class YourController : Controller
{
public ActionResult Index()
{
var model = YourDataToDisplay;
return View(model);
}
public ActionResult ControllerAction(int sales)
{
//.....
}
}
You can use ViewData to define ButtonText.
There are many ways to use link button in rezor ,try any of these
<button type="button" onclick="#("window.location.href='" +#Url.Action("ActionResult", "Controller") + "'")">
Link Button
</button>
<a href="#Url.Action("ActionResult", "Controller")">
Link Button
</a>
#Html.ActionLink("Text","ActionResult","Controller")
submitting form into the same page you have to use Ajax Begin Form or use simple json object with a ajax post method. Try like this
$("#btnSave").click(function (e) {
var urlpath = '#Url.Action("ActionResult", "Controller")';
$.ajax({
url: urlpath ,
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error !!!");
}
});
You can write an anchor tag. But clicking on the anchor tag usually does not submit the form, but triggers an HTTP GET request. So you need to write some java script to do the form submission.
<form action="Customer/Create">
Submit
</form>
Using jQuery and some unobtrusive javascript code to bind the click event on this anchor tag,
$(function(){
$("#linkToSubmit").click(function(e){
e.preventDefault(); // prevent the normal link click behaviour (GET)
$(this).closest("form").submit();
});
});
Now you can execute the code in your HttpPost action of Create action method in the Customer controller (because that is the form's action set to)
Another option is to keep the submit button inside your form and style it so that it looks like a link as explained in this answer.
if you are new to mvc then you need to check it's basic from MVC tutorials: Please follow below thread for convert your web app code to MVC
https://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink(v=vs.118).aspx
#Html.ActionLink("buttonText",new { controller = "ContreollerName", action = "ActionName",
#sales = "Your parameter" })
And then make a action result in your controller

manage serverside validaton when I use jquery post

From razor view I'm sending js object using jquery to the mvc controller. Reason why I do it using jquery post method and not razors form is that I need to manage dynamic input of certain fields. On the view certain fields (inputtextbox) are dynamically added to the view (from 0 - 10) and I manage that solution using js on the page.
var myJsObj = ...
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json',
url: '/MyController/SomeAction',
data: JSON.stringify({ model: myJsObj}),
success: function () {
}
});
On the server side, mvc receives that model and in case of some error I want to return this object back to the view.
[HttpPost]
public ActionResult SomeAction(MyModel model)
{
if(!ModelState.IsValid)
{
ModelState.AddModelError("", "Error occured!");
return View(model);
}
return RedirectToAction("Index");
}
I have inside razor view
Html.ValidationSummary
but since I'm using jquery post I dont know how to receive back to the view and display error like I would use regular razor form. Or if you know better approach to manage dynamically added input boxes on the razor view please post. Any help please.
I think you've got a couple of options here:
If you prefer to continue to use an Ajax POST as you've shown above, then you need to take the response from the POST and inject it back into your current HTML document. For example,
$.ajax({
type: 'POST',
traditional: true,
contentType: 'application/json',
url: '/MyController/SomeAction',
data: JSON.stringify({ model: myJsObj}),
success: function (data) {
// This is the case where the MVC action found model validation
// errors, and so it is responding with an HTML document that
// shows the errors.
var returnedBodyHtml = $(data).find('body').html();
$('body').html(returnedBodyHtml);
}
});
(That's untested code up there, so you may have to debug a little bit.) But this code doesn't handle the case where the server responded with a redirect (in the case of successful validation). So, check out this post for some options there.
Your other option is to use the standard Form submit. I know you said you had some dynamically generated input controls on your page, but that doesn't mean that you can't do a Form submit. You just need to make sure that these dynamically generated elements have the correct "name" attribute on them, so that their values get mapped appropriately to the Model on the server side action that is accepting the POST. For example, if your Javascript is dynamically generating an HTML element like this, and inserting it into the form:
<input type="text" name="myDynamicallyGeneratedInput[0]" />
<input type="text" name="myDynamicallyGeneratedInput[1]" />
<input type="text" name="myDynamicallyGeneratedInput[2]" />
<input type="text" name="myDynamicallyGeneratedInput[3]" />
then your Form submit will still work, as long as on the server side, your MyModel class has that corresponding property:
class MyModel
{
public List<string> MyDynamicallyGeneratedInput {get; set;}
}
This is what I have done to display errors for dynamic inputs. First off, take a look at this post to give you a better understanding. I have modified my code to better suit my needs, but you can check if it works for your application.
use-asp-net-mvc-validation-with-jquery-ajax.
I would then consume the return result in the ajax post error callback. It returns a code 400 'Bad Request' on validation errors. The validator variable is the form validator object.
error: function (xhr, textStatus, errorThrown) {
var statusCode = parseInt(xhr.status);
if (statusCode == 400) {
var data = $.parseJSON(xhr.responseText);
var message = "";
$.each(data, function (i, item) {
var propertyName = "" + item.key + "";
if ($("input[name='" + item.key + "']").length > 0) {
var errorObj = {};
errorObj[item.key] = item.error;
validator.showErrors(errorObj);
}
else {
message += "<div>" + item.key + ": " + item.error + "</div>";
}
});
if (message != "") {
//display message
}
}
}
I hope this helps. Good luck.

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>

update field or redirect page using jquery and asp.net mvc

Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).

Categories