How to update partial view from another partial view via action results - c#

I have three partial views on main view
on the first partial view I have search functionality and when user clicks on search I want to refresh results into 3rd partial view.
Controller:
public ActionResult Search()
{
virtualmodel vm = new virtualmodel();
return PartialView(svm);
}
[HttpPost]
public ActionResult Search(ViewModel svm)
{
// Query to retrive the result
// I am not sure what to return from here. Link to another action or just return back to same same partial
}
public ActionResult AnotherPartialPartial()
{
}
In main view
#{Html.RenderAction("Search", "Searchc");
}
How to do it? Do I need ajax?

Using ajax you can call a controller action and return it's response to a particular div.
Empty div:
<div class="row" id="div3">
</div>
Ajax to display html in empty div:
function performSearch(searchCriteria) {
//get information to pass to controller
var searchInformation = JSON.stringify(**your search information**);
$.ajax({
url: '#Url.Action("Search", "ControllerName")',//controller name and action
type: 'POST',
data: { 'svm': searchInformation } //information for search
})
.success(function (result) {
$('#div3').html(result); //write returned partial view to empty div
})
.error(function (xhr, status) {
alert(status);
})
}

jQuery will help you with it!
Try to handle submit button onclick event like this:
$("#yourButtonId").click(function()
{
$.ajax({
type: "POST",
url: "/yourUrl", //in asp.net mvc using ActionResult
data: data,
dataType: 'html',
success: function (result) {
//Your result is here
$("#yourContainerId").html(result);
}
});
});

You can do it with ajax.
First, change your html.beginform to ajax.beginform in your view and add div id into UpdateTargetId that you want to change contents. After updating first partial with ajax.beginform, you can update other partialviews with ajax.beginform's "OnSuccess" function. You have to add update function like that:
#using (Ajax.BeginForm("YourAction", "YourController",
new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" }))
{
/*your code*/
}
<script>
function OnSuccessMethod() {
$("#YouWantToChangeSecondDivID").load('/YourController/YourAction2');
$("#YouWantToChangeThirdDivID").load('/YourController/YourAction3');
};
</script>
Then in your controller, return a partial view to refresh your view part that you entered it's ID in UpdateTargetId value:
public ActionResult YourControllerName(YourModelType model)
{
...//your code
return PartialView("_YourPartialViewName", YourViewModel);
}
Note: Don't forget to add reference to "jquery.unobtrusive-ajax.min.js" in your view while using ajax.

So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
#{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('#Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}

Related

How to pass variable from form to ajax in ASP.NET CORE 2.2

I have page with an item list and I need to add them to shop cart. I need to add them with ajax, I did write ajax request, so how should I pass vars to ajax and then send to controller:
function AddToCart(id) {
$.ajax({
url: "/CartNancy/Add",
type: "POST",
data: {
id : id
},
success: function () {
prompt("Added to cart");
}
});
}
And this is form
<form method="post">
<input name="Id" value="#item.Id" class="btn btn-success" hidden>
<button onclick="AddToCart()" class="btn btn-success">Add to cart</button>
</form>
Controller
[HttpPost]
public JsonResult Delete(string id) {
_bookService.Remove(id);
return new JsonResult("Deleted");
}
To force Web API to read the simple id from the request body, add the [FromBody] attribute to the parameter:
[HttpPost]
public JsonResult Delete([FromBody]string id) {
_bookService.Remove(id);
return new JsonResult("Deleted");
}
You can check the full doc here:
Try adding [FromBody] to the parameter:
[HttpPost]
public JsonResult Delete([FromBody]string id) {
_bookService.Remove(id);
return new JsonResult("Deleted");
}
you defined the function with the id parameter but did not send it when calling. can't see add to cart function on controller.
if you want to add that hidden value to ajax request then..
function AddToCart() {
var id = document.getElementsByName("id")[0].value;
$.ajax({
url: "/CartNancy/Add",
type: "POST",
data: {
id : id
},
success: function () {
prompt("Added to cart");
}
});
}

Ajax.BeginForm render wrong url in mvc

I am trying to load a div data using ajax rather than whole view on post method.
but it returns object%20HTMLInputElement action name on post action.
Controller:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
return View();
}
View
<div id="divEmp">
#using (Ajax.BeginForm("Index", "Challan", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
{
#Html.AntiForgeryToken()
<h3 style="text-align:center;" class="row header">Challan Data</h3>
#Html.Partial("_DateCommonFT")
}
It includes _Layout.cshtml where i have defined scripts as:
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
How to render only post action without loading whole page (_layout.cshtml) on post request using ajax.
Can you try to close your div tag and receive HtmlForgeryToken in controller like following.
you can also fill your target div with PartialView by returning PartialView() in Index method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(DemoCLass objdemo)
{
return PartialView();
}
<div id="divEmp">
</div>
#using (Ajax.BeginForm("Index", "Challan", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp" }))
{
#Html.AntiForgeryToken()
<h3 style="text-align:center;" class="row header">Challan Data</h3>
#Html.Partial("_DateCommonFT")
}
please Ajax.Begin form you can use OnSuccess method.
In VIew:-
#using (Ajax.BeginForm("Index", "Challan", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEmp", OnSuccess = "AjaxForm" }))
{
}
In Script:-
here return json from post controller.
function AjaxForm(response){
.....do as uou want...
}
in Controller:-
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
return json(new {IsSuccess = true},JsonRequestBehavior.AllowGet);
}
if you have any query in this one then tell to me
Use the PartialView method to return a view without the layout.
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
return PartialView();
}
If you want to return the html without layout markup only for the ajax form submissions, you can check the request headers to see whether the request is an xhr request or not. Request.IsAjaxRequest() method will be handy here.
[HttpPost]
public ActionResult Index(DemoCLass objdemo)
{
if (Request.IsAjaxRequest())
{
return PartialView();
}
else
{
return View();
}
}

C# : Calling controller method from view folder

I'm totally a noob to MVC Framework. And I want to call my Agentcontroller's action method which is in the Controller folder.
I'm trying to call
Controller/Agentcontroller/myactionmethod()
from View Folder
View/Agent/CodeGenerate.cshtml
I think I'm having trouble with the route but I can't find the App_Start folder. This is the script I'm using.
<script type="text/javascript">
function G() {
$.ajax({
type: "post",
url: '/AgentsControllers/',
data: $('form').serialize(),
success: function (response) {
alert("Hi");
}
});
}
</script>
I've also checked this out as well: MVC - calling controller from view
Thanks in advance!
Your Ajax call should be :
<script type="text/javascript">
function G() {
$.ajax({
type: "post",
url: '/AgentsControllers/myactionmethod/',
data: $('form').serialize(),
success: function (response) {
alert("Hi");
}
});
}
</script>
And your Controller Action Method Should be :
[HttpPost]
public ActionResult myactionmethod(YourModelName objYourModelobject)
{
return PartialView("~/Views/Agent/CodeGenerate.cshtml", objYourModelobject);
}
And Your View Should be :
#model Application.Model.YourModel
#using (Html.BeginForm("Agentcontroller", "myactionmethod", FormMethod.Post, new { #class = "example" }))
{
//HTML Helpers
#Html.HiddenFor(model => model.Id, new { #id = "hdnDetailId" })
<button type="submit" class="btn btn-success" id="btnSave"><i class="fa fa-floppy-o"></i> Save</button>
}

Asp.Net load data by button click

I have a simple list view where I'm loading my data.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Your application description page.";
IList<Product> products;
using (ISession session = NHibernateSession.OpenSession()) // Open a session to conect to the database
{
products = session.Query<Product>().ToList(); // Querying to get all the books
}
return View(products);
}
}
View is a simple list view from template.
Now, I need to load data to list view just after button click.
So as I understand I need to render partial view.
I've add this to view:
<button id="Load">Load data</button>
<script type="text/javascript">
var url = '#Url.Action("LoadData", "Home")';
$('#Load').click(function() {
var keyWord = $('#Keyword').val();
$('#result').load(url);
})
</script>
<div id="result"></div>
And add controller action:
public ActionResult LoadData()
{
// here will be model creation and passing view
return PartialView();
}
But controller action doesn't get called.
What should I do?
This is now I would do it.
We create an action method which return JSON on http gets
public class SomeController : Controller
[HttpGet]
public ActionResult LoadData()
{
using (ISession session = NHibernateSession.OpenSession()) // Open a session to conect to the database
{
products = session.Query<Product>().ToList(); // Querying to get all the books
}
return Json(new {data=product},
JsonRequestBehavior.AllowGet);
}
Inside your view we do a ajax request to get the data by calling LoadData
$.ajax({
type: 'get',
dataType: 'json',
url: 'SomeController/LoadData',
success: function (data) {
//Render data to view maybe using jquery etc
},
error: function(data) {
//Notify user of error
}
});
Hope this helps man

Issue while calling action method with ajax contentType

I have an application that need to post back through Ajax. Getting problem while calling the ActionMethod. below are the code.
Controller :
[HttpGet]
public ActionResult Index()
{
return View();
}
public JsonResult AjaxTest(object name)
{
return Json("Welcome" + name, JsonRequestBehavior.AllowGet);
}
Cstml :
<form name="frmTest" method="POST">
#Html.Label("Your name Please")
#Html.TextBox("username")
<input class="btn btn-success btn-lg btn-block" type="submit" value="Login">
JQuery :
$(function () {
$("form[name='frmTest']").submit(function (e) {
var name = $('#username').val();
$.ajax(
{
type: "POST",
//contentType: "application/json; charset=utf-8",
url: "MyTest/AjaxTest",
dataType: "json",
data: { name:name },
success: function (data, status) {
alert("Pass"+data);
},
error: function () {
alert("Fail");
}
});
});
});
By using the above code break point hit to AjaxTest with the parameter. when I use contentType: "application/json; charset=utf-8", then the page postedback without hitting the break point.
But both cases I got fail alert. unable to find the issue,
I am not sure what you are trying to do but since in one of the comments you stated you will be saving stuff to the database, normally, in ASP MVC it would be done like this.
Create a class for whatever you will be posting using AJAX. For example, in this example, I created a class called Person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Then in your form you can have something like this:
#{
ViewBag.Title = "Test";
}
<form name="frmTest" method="POST">
#Html.Label("Your name Please")
#Html.TextBox("username")
<input class="btn btn-success btn-lg btn-block" type="submit" value="Login">
</form>
<script>
$(function () {
$("form[name='frmTest']").submit(function (e) {
var name = $('#username').val();
$.ajax(
{
type: "POST",
//contentType: "application/json; charset=utf-8",
url: "AjaxTest",
dataType: "json",
data: { "Age": 55, "Name": name },
success: function (data, status) {
alert("Pass" + data);
},
error: function (ex) {
alert("Fail" + ex);
}
});
});
});
</script>
Then have an action which the JSON will be submitted to. For the above, the action will be like this:
public JsonResult AjaxTest(Person person)
{
return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet);
}
ASP MVC will take care of the binding for you. Please also note the url I am posting is "AjaxTest" and it will post to AjaxTest action method of the controller which served the form.
If you have a controller like below, then all of the above will work.
public class AccountController : Controller
{
// This returns the view with the form
public ActionResult Test()
{
return View();
}
public JsonResult AjaxTest(Person person)
{
return Json("Welcome" + person.Name, JsonRequestBehavior.AllowGet);
}
}

Categories

Resources