I have button. I want to route new view when i clicked the button. The button is like below:
<button type="button" id="btnSearch" class="btn btn-warning" style="height:35px;width:120px"> <i class="fa fa-search" aria-hidden="true"></i> <translate>Search</translate> </button>
when button is clicked and than the method which is below run:
$('#btnSearch').click(function () {
return $.ajax({
url: '@Url.Action("test", "ControllerName")',
data: { Name: $('#Name').val() },
type: 'POST',
dataType: 'html'
});
});
my controller action is below:
public ActionResult test(string CityName) {
ViewBag.CityName = CityName;
return View();
}
when i debug my program, flow came to my controller action. But index web page don't route to the test view page. Error is not occurred. What can i do for this state ?
Then, Jquery use it to populate a table or something. :) Yes, you can return view from the controller and append via Ajax. For that, you need to render the view in the controller before returning it.
A controller action might return a view. However, a controller action might perform some other type of action such as redirecting you to another controller action.
This even works without parameters, so at that point, you might wonder how in the world a Controller knows exactly which of your Views to return for a specific Action. The answer is something called View Discovery - a process where ASP.NET MVC will try to guess which View to use, without forcing you to specify it.
If you wants to refresh page:
Controller:
public ActionResult Index()
{
return View();
}
public ViewResult Test()
{
ViewBag.Name = Request["txtName"];
return View();
}
Index.cshtml:
@using (Html.BeginForm("Test", "Home", FormMethod.Post ))
{
<input type="submit" id="btnSearch" class="btn btn-warning" style="height:35px;width:120px" value="Search"/>
<label>Name:</label><input type="text" id="txtName" name="txtName" />
}
Test.cshtml:
@ViewBag.Name
=============================================
If you don't wants to refresh page:
Controller:
public ActionResult Index()
{
return View();
}
[HttpPost]
public PartialViewResult TestAjax(string Name)
{
ViewBag.Name = Name;
return PartialView();
}
Index.cshtml:
<input type="button" id="btnSearch" class="btn btn-warning" style="height:35px;width:120px" value="Search"/>
<label>Name:</label><input type="text" id="txtName" name="txtName" />
<script>
$('#btnSearch').click(function () {
$.ajax({
url: '@Url.Action("TestAjax", "Home")',
data: { Name: $("#txtName").val() },
type: 'POST',
success: function (data) {
$("#divContent").html(data);
}
});
});
</script>
TestAjax.cshtml:
@ViewBag.Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With