1

I want to call a controller method which returns a string value from view, for example suppose I have a controller method public string Username(string email). I want to call this method in view so that I can assign return Value i.e. User name to my label.

So I have two question :-

  1. How to call this parameterized controller function in view "public string Username(string email)".
  2. And get its return value.

4 Answers 4

5

if you want to display it:

@{Html.RenderAction("Username", "ControllerName" , new {email="your email"});} 

If you want to call it through ajax, use '@Url.Action("Username", "ControllerName" , new {email="your email"})' as url in your ajax request

Sign up to request clarification or add additional context in comments.

Comments

1

Use the below code , also add [HttpPost] attribute above controller action method

 $.ajax({
 // method: 'POST', <-- remove this
 type: 'POST', // <-- add this
 url: '@Url.Action("ActionName","ControllerName")',
 dataType: 'json',
 data: { id: 'Parameter' },
 success: function (data, textStatus, jqXHR) {
    //the data here is returned from your controller action method
 console.log("success");
 },
 error: function () {
     alert('error');
 }
 });

1 Comment

Abhishek, you could upvote the answer in case it was helpful.. :)
0

View side

@model String
<label>Model</label>

Controller Side

public ActionResult ReturnString()
{
var user=userName//Get user name
return View(user)
}

Comments

0

Take a look at AJAX. If you are using JQuery, this task can be done with the ajax function. In your case the javascript would look something like this:

    $.ajax({
        url: '@Url.Action("Username")',
        data:  { email: "[email protected]" },
        success: function (result) {
                $('#YourLabel').val(result);
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.