Linkbutton equivalent in MVC C# Razor - c#

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

Related

ASP Core 2.0 - Calling Controller Functions from a View

I'm a complete beginner with ASP Core and web development in general, so I apologize if this is painfully obvious.
I am looking for a way to call a function that is present in my Controller from my View. This function would be called in reaction to the user clicking a button on their webpage.
Controller Function:
public ActionResult Change(int n)
{
ViewData["currentChoice"] = choiceArray[n];
return View();
}
View:
#{
Choice currentPoint = ViewData["currentChoice"] as Choice;
<h2>#currentPoint.text</h2>
}
//Button - Call Change function in the Controller
I have previously created a button that links to another page, in this case "Question/Change", but I do not want a redirect. The desired final result would simply update the text on the screen by changing the ViewData.
In MVC Controller Actions(functions) are invoked through http requests that originate from your view in the form of anchor elements, AJAX calls, or form submissions.
MVC has nice helpers to generate correct URLs for anchor elements that map to your action of choice.
#{
Choice currentPoint = ViewData["currentChoice"] as Choice;
<h2>#currentPoint.text</h2>
}
Change
Try this
as you are using ASP.NET core so your anchor tag should be like this
<a asp-controller="YourControllerName" asp-action="Change" class="btn btn-primary" onClick="changeChoice()">Change</a>
add JS
<script type="text/javascript">
$('document').ready(function ()
{
function changeChoice()
{
$.ajax(
{
url: '/YourControllerName/Change
type: 'GET',
success: function (response) {
alert('Successfully Updated'),
location.reload()
},
});
}
});
</script>

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.

Can't call new page by controller in Asp.net

I want to call new page by click on a button by jQuery from Index.cshtml :
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
}
});
});
});
It call to my controller action : UserController/getAll
[System.Web.Services.WebMethod]
public ActionResult getAll(string id,string name)
{
return View("AllUser");
}
But is still at Index.cshtml not go to AllUser.cshtml page? I don't know why...please help.
UPDATE :
my jquery function call my action in controller , and the action work correctly but it not return to AllUser.cshtml page.
Please check out the documentation here. I would attempt using a tag-helper in the Ajax setup like this:
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: '#Url.Action("User", "getAll", new { id = "ID", name = "searchName" })',
id : idser,
success: function() {
alert("success");
}
});
});
});
Firstly I don't know what is your purpose behind using ajax while your are redirecting the other page ?
But you if still want to use Ajax, you can achieve this by two ways:
1) you can assign window.location in your success block.
2) Use your code by following way :
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "GET",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
return true;
}
});
});
});
you can try it by putting return true in your script.
hope it helps to you
Updating in response to clarification in comments:
In the success callback,
location.href="/user/getall";
That will cause the browser to navigate to that URL after the ajax post has completed.
A button that posts a value from an input to another page - that's a form.
<form action="/User/getAll">
<input type="submit" value="Click me">
</form>
I don't know where your id is coming from, but you can put a hidden input in the form and a script to populate it (unless it's a user input - then you can just put the input right in the form.)
<form action="/User/getAll">
<input type="submit" value="Click me">
<input type="hidden" name="id" id="hiddenId"/>
</form>
<script>
$("#hiddenId").val($("#Name").val());
</script>
Or, if you want to be sure that your form's action URL matches your route:
<form action='#Url.Action("getAll", "User")'>
(Assuming that the controller is called "User".)
Here we go:
window.location.href = "yourUrl" can help you.
$("#btnSearch").click(function(){
var idser = $("#Name").val();
$.ajax({
type: "POST",
url: "/User/getAll",
id : idser,
success: function() {
alert("success");
window.location.href ="../yourUrl"; //This is working!
}
});
});
});
You may redirect in Controller this like:
[System.Web.Services.WebMethod]
public ActionResult getAll(string id,string name)
{
return RedirectToAction("NameOfAction"); //Here is going Name of Action wich returns View AllUser.cshtml
}
Hope it helps;)

Unable to send back data to action in MVC controller from javascript

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.

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