I’m trying to return the content from the controller to the view but for some reason, it doesn’t work. I want the text from the "return Contect (….)" to replace the label.
Here is my code from the controller:
namespace Assignment.Controllers
{
public class Q2Controller : Controller
{
// GET: Q2
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult ValidateInput(string myInput)
{
string temp = "";
for (int i = myInput.Length - 1; i >= 0; i--)
{
temp += myInput[i].ToString();
}
if (temp == myInput)
return Content("The string is palindrome");
else
return Content("The string is not palindrome");
}
}
}
And here is the View:
<body>
<p>Please enter an alphanumeric string:</p>
<div class="lbl">
@Html.Label("lblpalindrome", "Is it palidrome?")
</div>
<div class="content">
@Html.TextBox("myInput");
<input id="btn1" type="button" value="Enter" onclick="ValidateInput()" />
</div>
</body>
<script>
function ValidateInput() {
var result="";
$.ajax({
url: "@Url.Action("ValidateInput", "Q2")",
type: "POST",
cache: false,
async: true,
data: { myInput: $('#myInput').val() },
success: function (response.data) {
$("#lblpalindrome").text(response.data);
},
error: function (response.data) {
alert("An error occurred: " + response.data);
}
});
}
</script>
2
Answers
As you’re just returning a plain string response, then there’s no
data
property in theresponse
argument of thesuccess
handler function.response
itself is the text value:That being said, returning a plain text response is not a good pattern to follow. Use a serialised format as it’s more extensible and reliable. In this case I’d suggest using JSON:
This could be taken a step further still by using a common class for the response. In addition, there are better ways to reverse a string than using a loop.
You also can do this way without server side call :