Simple Ajax call posting back entire page - c#

I want to call and return data from a controller action asynchronously using Ajax.
In my example below, when clicking on the ActionLink it posts back to a new page with just "Hello!". How can I get this to just update the div?
Controller:
public class HelloAsyncController : Controller
{
public ActionResult Index()
{
return View();
}
public string Hello()
{
return "Hello!";
}
}
View:
#Ajax.ActionLink("Say Hello", "Hello", "HelloAsync",
new AjaxOptions()
{
UpdateTargetId = "HelloDiv"
})
<div id="HelloDiv"></div>
Includes in _Layout.cshtml:
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
I am using MVC 5.

Have you tried using
#Ajax.ActionLink(
"Say Hello",
"Hello",
"HelloAsync",
new AjaxOptions
{
UpdateTargetId="HelloDiv",
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace
})
I thing that issue might be
The contents of the UpdateTargetID must be in a partial view and that
partial view needs to be called from the Controller Action. . You need to use a
partial view.
Also check
Check if files MicrosoftAjax.js and MicrosoftMvcAjax.js are really
present in ../../Scripts folder.

Related

Simplest way to get model data/objects in the view from input with an ajax partial view call(s)

Hello i googled to find a solution to my problem, every link brought me to asp forms solution, or solutions that do not ask for form inputs, this problem has form inputs and i cant seem too find a link for help, what im asking for is simple: get the data from user input through models by ajax calls.
View (index.cshtml):
#model UIPractice.Models.ModelVariables
<!-- Use your own js file, etc.-->
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<div id="div1">
#Html.BeginForm(){ #Html.TextBoxFor(x => x.test1, new { style = "width:30px" })}
<button id="hello"></button>
</div>
<div id="result1"></div>
<script type="text/javascript">
//Job is to load partial view on click along with model's objects
$(document).ready(function () {
$('#hello').click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("HelloAjax", "Home")',
data: $('form').serialize(),
success: function (result) {
$('#result1').html(result);
}
});
});
});
Model (ModelVariables.cs):
public class ModelVariables
{
//simple string that holds the users text input
public string test1 { get; set; }
}
Controller (HomeController.cs):
// GET: Home
public ActionResult Index()
{
ModelVariables model = new ModelVariables();
return View(model);
}
public ActionResult HelloAjax(ModelVariables model)
{
ViewBag.One = model.test1;`
return PartialView("_MPartial", model);
}
Partial View (_MPartial.cshtml):
#model UIPractice.Models.ModelVariables
#{
<div>
<!--if code runs, i get a blank answer, odd...-->
#Model.test1
#ViewBag.One
</div>
}
So go ahead and copy/paste code to run, you will notice that you get nothing when you click the button, with user text input, odd...
I see a few problems.
Your code which use the Html.BeginForm is incorrect. It should be
#using(Html.BeginForm())
{
#Html.TextBoxFor(x => x.test1, new { style = "width:30px" })
<button id="hello">Send</button>
}
<div id="result1"></div>
This will generate the correct form tag.
Now for the javascript part, you need to prevent the default form submit behavior since you are doing an ajax call. You can use the jQuery preventDefault method for that.
$(document).ready(function () {
$('#hello').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '#Url.Action("HelloAjax", "Home")',
data: $('form').serialize(),
success: function (result) {
$('#result1').html(result);
}
,error: function (a, b, c) {
alert("Error in server method-"+c);
}
});
});
});
Also, you might consider adding your page level jquery event handlers inside the scripts section (Assuming you have a section called "scripts" which is being invoked in the layout with a "RenderSection" call after jQyery is loaded.
So in your layout
<script src="~/PathToJQueryOrAnyOtherLibraryWhichThePageLevelScriptUsesHere"></script>
#RenderSection("scripts", required: false)
and in your indidual views,
#section scripts
{
<script>
//console.log("This will be executed only after jQuery is loaded
$(function(){
//your code goes here
});
</script>
}

Update only the partial view [duplicate]

I want to show a success message after calling the following ajax.beginform
from Index view
#using (Ajax.BeginForm("Insert", "Home", new AjaxOptions() { UpdateTargetId = "result", HttpMethod = "POST" }))
{
#Html.TextAreaFor(m => m.openion)
}
this is my result div
<div id="result">
</div>
and my controller is
[Httppost]
public ActionResult InforMessage(openionModel usr)
{
return Content("Thanks for adding your openion");
}
but when i try this it is going to another view InforMessage
It is not updating the result div.
There is no Informessage Exist. Still it open a new page with message
"Thanks for adding your openion".How to solve this?
If your redirecting to another page its because you do not have the correct scripts loaded (or have duplicates or have them in the wrong order) so its doing a normal submit.
Ensure you have included (in order)
jquery-{version}.js
jquery.unobtrusive-ajax.js

Updating layout part dynamically

C# asp.net MVC project: I have my index page with a button in it, I want to press it and update the same page with some results.
Here's some code:
The View: (with a button that calls the getConfig method in the controller)
#{
ViewBag.Title = "Home Page";
}
<form method="get" action="/Home/GetConfig/" >
<input type="submit" value="Get Config WS" />
</form>
<p>
#ViewBag.totalRecords
</p>
The controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Test webservices";
return View();
}
public void getConfig()
{
string totalRecords = string.Empty;
wsConfig.config_pttClient client = new wsConfig.config_pttClient();
wsConfig.getConfigInput gci = new wsConfig.getConfigInput();
wsConfig.getConfigOutput gco = new wsConfig.getConfigOutput();
gco = client.getConfig(gci);
totalRecords = gco.result.totalRecords.ToString();
ViewBag.totalRecords = totalRecords;
}
I want to press the view's button and show the totalRecords on the same page.
How can I achieve this?
Edit: There might be other solutions, (if you don't mind updating your entire page) but this how I generally do it.
Ok, there are a couple of things that you need to change in order to make it work:
Create a new partial view that contains just the part that you would like to update (and wrap it an element with an id). In this example, let's call it 'Partial_TotalCount'.
This partial view will contain the following code:
<div id="updated">
<p>
#ViewBag.totalRecords
</p>
</div>
Now, change your original view so that it includes the partial view:
#{
ViewBag.Title = "Home Page";
}
<form method="get" action="/Home/GetConfig/" >
<input type="submit" value="Get Config WS" />
</form>
#Html.Partial("Partial_TotalCount", #Model)
Now, update your controller to work with an ajax request. This would make your controller looks like:
public ActionResult Index()
{
ViewBag.Message = "Test webservices";
if (Request.IsAjaxRequest())
{
getconfig();
return PartialView("Partial_TotalCount");
}
return View();
}
Now, you need to be able to submit the page when you click the button. This can be done through javascript:
First your javascript function that will update the contents:
<script type="text/javascript">
function Refresh() {
$.ajax({
url: '/Home/Index',
type: "GET",
dataType: "html",
success: function(data) {
$("#updated").html(data);
},
error: function() { alert('Refreshing error.'); }
});
}
</script>
You just need to add an onclick on your button. And you can remove the form tags from around your form aswell.
Edit: As requested by the questioner, I provide a bit of explanation on the Javascript function itself:
$.ajax means that we are doing an Ajax request. It means that we are doing some asynchronous requests with the server.
Then a couple of parameters are passed:
Url: The url that should be executed. In your example, the code behind the url "Home/GetConfig" get's executed.
Type: The type of submit that you want to do (POST, GET, ...)
dataType: The type we are expecting back from the server.
Success: The piece of javascript that needs to execute when complete. (In this case, update the DIV element with the id "WithCss" with the contents that are received with the url "Home/Getconfig".
Error: A function that is executed when the request failed for some reason.
There are a lot of other parameters you can pass (for example if you need to pass an id, and others.
For more explanation, please look at the original documentation.
Also, consider marking this answer as accepted.
I hope it works.
Try This:
Replace your input button code with the following code :
<input type="submit" id="btnSave" name="BtnSave" value="Get Config WS" />
Then in controller change the whole code for this code:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Test webservices";
return View();
}
public ActionResult getConfig()
{
return View();
}
[HttpPost]
public ActionResult getConfig(FormCollection Form)
{
if(Form["BtnSave"]!=null)
{
string totalRecords = string.Empty;
wsConfig.config_pttClient client = new wsConfig.config_pttClient();
wsConfig.getConfigInput gci = new wsConfig.getConfigInput();
wsConfig.getConfigOutput gco = new wsConfig.getConfigOutput();
gco = client.getConfig(gci);
totalRecords = gco.result.totalRecords.ToString();
ViewBag.totalRecords = totalRecords;
}
return View();
}
Hopefully it works...!

Ajax.BeginForm PartialView not refreshing

I am using asp.net mvc 4. I've searched many other similar questions here, but they didn't help.
I want to refresh my partial view - FileList after uploading file.
Instead I see now redirecting to page with updated file list, but i want to refresh this list in partial view. :(. Can anybody help? Another solutions to do similar features are acceptable :)
My partial view is in another (index) partial view.
Here is FileController:
private static int folderId = 0;
public ActionResult Index(int id)
{
folderId = id;
this.GetFiles();
return PartialView();
}
public PartialViewResult FileList()
{
this.GetFiles();
return PartialView("FileList");
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult UploadFiles(IEnumerable<HttpPostedFileBase> filesToUpload)
{
this.UploadFilesToBase(filesToUpload, 1);
this.GetFiles();
return PartialView("FileList");
}
and here is Index.cshtml
<script src="#Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-2.6.2.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/main.js")" type="text/javascript"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
#using (Ajax.BeginForm("UploadFiles", "File", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "FilesListDiv", InsertionMode = InsertionMode.Replace }, new { enctype = "multipart/form-data" }))
{
<div class="btn-upload-file">
#Html.AntiForgeryToken()
<span class="btn"><span>Upload file</span></span>
<input type="file" class="file" name="filesToUpload" multiple onchange="javascript:this.form.submit();"><br>
</div>
}
<div id="FilesListDiv">
#*#Html.Action("FileList", "File")*#
#Html.Partial("~/Views/File/FileList.cshtml")
</div>
and here is my FileList.cshtml
#{
Layout = null;
ViewBag.Title = "Files";
}
#foreach (MyProj.Web.DataContracts.File file in ViewBag.Files)
{
file.Name
}
Your ajax form doesn't work, probably because you haven't included jquery.unobtrusive-ajax.js into the page and as a result, it works like a regular html form.
As soon as you add this file, you will be able to refresh the content via ajax, but filesToUpload will be null in the controller. The reason for that is impossibility of uploading files via ajax, because it does not support multipart/form-data enctype.
You can try to use some jQuery upload plugins ot HTML 5 File API.
Use this plugin http://malsup.com/jquery/form/ and this will submit form without the refresh. When you got the file uploaded on server then you can make a callback on the success of upload.
Get the list of file from server as render as html (through partialresult) and update them on client side browser.

MVC 3: What's the most common way of asynchronously loading form fields based on previous choices?

Imagine having two list boxes on a form, where the choices in the second depend on what's been picked in the first. What's the most common, or cleanest way of going about this with MVC3?
I would say that you would need two things to accomplish this cleanly; Ajax and a Json ActionResult
$('#listbox').change(function() {
$.ajax({
url: '/ListBoxChange',
method: 'POST',
data: {
listBoxValue: 'The value'
},
success: function(data) {
alert (data.Result);
}
});
});
The Action Result:
[HttpPost]
public ActionResult ListBoxChange(string listBoxValue)
{
string result = GetResult();
return Json(new {
Result = result
});
}
Alternatively can use the MVC framework, directly binding back to view after a partial refresh. I've used the following for complex dynamic searches, works decently.
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>" type="text/javascript"></script>
<% using (Ajax.BeginForm("/GetProducts",
new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnBegin = "beginSearchLoader",
OnComplete = "completeSearchLoader",
UpdateTargetId = "divSelectionResult"
}
))
{ %>
<div id="divSelectionResult">
<% Html.RenderPartial(Html.ProductViewPath("ProductContainer") , Model); %>
</div>
public ActionResult GetProducts(FormCollection form)
{
//search parameters used in Form
ProductModel modelData = Search(form);
ViewData.Model = modelData;
//AJAX Partial View Return
return PartialView(Constants.VIEW_FOLDER + "ProductContainer" + Constants.PARTIALVIEW_EXTENSION);
}
FYI: Some of the code is using custom helpers and etc.

Categories