problem asp.net mvc cannot load ajax content - ajax

in my view:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../jquery-1.4.1-min.js" type="text/javascript"></script>
<%= Ajax.ActionLink("Update", "Index", "Home", new AjaxOptions { UpdateTargetId = "time" })%>
<br />
<div id="time">
<% Html.RenderPartial("TimeControl"); %>
</div>
in my controller:
[HttpGet]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
// Normal Request
if (!Request.IsAjaxRequest())
{
return View("Index", model);
}
// Ajax Request
return PartialView("TimeControl");
}
in my model:
public HomeModel()
{
Time = DateTime.Now;
}
i think everything is ok, but if iam clicking update link, time will be not updated.. why?
it schould be actual if i click update link

I suggest you do the following:
[HttpGet]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
return View("Index", model);
}
[HttpPost]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
// Ajax Request
return PartialView("TimeControl");
}
I think the problem might be that the AJAX request is a POST.

You may simply try to (1) remove [HttpGet] or (2) set the HttpMethod in the AjaxOptions to "GET".
Ajax.ActionLink("Update", "Index", "Home", new AjaxOptions { UpdateTargetId = "time", HttpMethod = "get" })
That should solve the problem.
(3) If it doesn't, check if you are using the correct overload. This should work:
Ajax.ActionLink("Update", "Index", "Home", null, new AjaxOptions { UpdateTargetId = "time" }), null)

Any of the options in my previous answers could solve your problem if the AJAX isn't working correctly with your application.
Buy in your example, you're also using something that wasn't quite clear to me.
You use a constructor overload that takes the url. And you use the default constructor to set the time. Is the constructor you use (the one that takes the url) also calling the parameterless constructor?
That constructor should do something like this:
public HomeModel(paramter.......) : this()
{
// Whatever...
}

Related

Adding 'Edit' Ajax.ActionResult to render on same page in MVC

My first ever Ajax request is failing, and I'm not quite sure as to why.
I've used the MVC scaffolding in order to create a table (which uses a default #Html.Actionlink). However, I'm looking to include an 'edit' section on the same page via ajax requests.
So my table now has:
<td>
#Ajax.ActionLink("Edit", "Edit", new { id=item.OID}, new AjaxOptions {
UpdateTargetId = "editblock",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET" }
) |
As suggested here.
Within the same view i have a div defined as:
<div id="editblock">
Edit Section Here
</div>
And My controller is defined as:
public PartialViewResult Edit(int? id)
{
if (id == null)
{
return PartialView(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
}
TableModel tablevar = db.TableModel.Find(id);
if (tablevar == null)
{
return PartialView(HttpNotFound());
}
return PartialView("Edit", tablevar );
}
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult Edit( TableModel tablevar )
{
if (ModelState.IsValid)
{
db.Entry(tablevar ).State = EntityState.Modified;
db.SaveChanges();
}
return PartialView("Edit",tablevar );
}
My "Edit.cshtml" looks like:
#model Project.Models.TableModel
<body>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
Could anyone suggest as to why this is failing, and what I should be doing instead to render this partial view onto the page (as currently it keeps redirecting to new page and not showing on 'index' screen)?
Place those scripts at the bottom of your view. By the time they execute your form isn't present (and therefore the auto-wireup fails). In general, you want <script> tags as close to the </body> tag as possible to your content is there before the script executes.
Other than that, you look fine.

Pass selected item ID into partial view

I am building a page where a user can view the details of an item which s/he selected.
As part of this project, I need to show all the comments that are listed under this particular item using Ajax and partial views.
In the Controller class, I am somehow unable to pass the productID of the selected item to the partial view method. When I hard code the productID into the method, the comments show up, however when I pass it through the parameter, the method won't even trigger.
All the product details, however, show without restrictions.
I would appreciate any help. Below please find the code in my Controller
public ActionResult Index()
{
List<Product> productList = new ProductClient().GetAllProducts().ToList();
return View("Index", productList);
}
//This method works correctly. The id of the product is passed.
public ActionResult Details(int id)
{
return View(new ProductClient().GetProductByID(id));
}
// This method is not even getting triggered.
public PartialViewResult ProductComments(int id)
{
List<Comment> commentList = new ProductCommentClient().GetCommentsByProductID(id).ToList();
return PartialView("_comments", commentList);
}
This is my Details.cshtml
#Ajax.ActionLink("Product Comments", "ProductComments(" + #Model.ID + ")", new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId= "divComments",
InsertionMode = InsertionMode.InsertAfter
})
<fieldset>
<div id="divComments">
<legend>Comments</legend>
</div>
</fieldset>
Many thanks in advance.
I solved this.
#Ajax.ActionLink("Product Comments", "ProductComments", new {id=Model.ID}, new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId= "divComments",
InsertionMode = InsertionMode.InsertAfter
})
<fieldset>
<div id="divComments">
<legend>Comments</legend>
</div>
</fieldset>
I was passing the ID in the wrong manner. I hope that this would at least help somebody else.

Result not showing with unobtrusive ajax in mvc 3

I'm trying to implement a little ajax using unobtrusive ajax of mvc 3. Here is the code snippet:
Controller:
[HttpGet]
public ActionResult ViewEmployee()
{
return View();
}
[HttpPost]
public ActionResult ViewEmployee(EMPLOYEE model)
{
var obj = new EmployeeService();
var result=obj.FindEmployee(model);
return View("ViewEmployee", result);
}
View:
#{AjaxOptions AjaxOpts = new AjaxOptions { UpdateTargetId = "ajax", HttpMethod = "Post" };}
#using (Ajax.BeginForm("ViewEmployee", "Home", AjaxOpts))
{
#Html.LabelFor(x => x.EmployeeID)
#Html.TextBoxFor(x => x.EmployeeID)
<input type="submit" name="Find Name" value="Find Name" />
}
<div id="ajax">
#{
if (Model != null)
{
foreach (var x in Model.EmployeeName)
{
#x
}
}
else
{
#Html.Label("No Employee is selected!")
}
}
</div>
I debugged the code, its sending the employee id to the ViewEmployee method, finding the name but not being able to display the name back into the view.
I've activated the unobtrusive ajax property in web.config & imported the scripts into the view.
Whats going wrong with this? Please help.
This is simple but effective article, ask me if you have any more question! I resolved the problem! By the way, whats wrong with stackoverflow, i'm not getting no response literally!
http://www.c-sharpcorner.com/UploadFile/specialhost/using-unobtrusive-ajax-forms-in-Asp-Net-mvc3/

mvc partial view ajax update returning the partial view as a page

I have a partial view that upon adding an item to the database needs to update.
The Index.cshtml:
#using (Ajax.BeginForm("Index", "WinEntry", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "wingrid", InsertionMode = InsertionMode.Replace}))
{
#Html.Partial("_winVenue")
#Html.Partial("_singleWin")
}
<div id="wingrid">
#Html.Partial("_wingrid")
</div>
The _singleWin has the submit button
The controller:
[HttpPost]
public ActionResult Index(Win win)
{
win.dealerId = "1234567890";
win.posterid = "chris";
win.posttime = DateTime.Now;
wem.addWin(win);
IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
return PartialView("_wingrid",w);
}
When the controller returns the partial view _wingrid it returns it as a new page and the behavior I am looking for is like an update panel inside the wingrid div.
Any help would be appreciated.
You already seem to be doing this thanks to the UpdateTargetId = "wingrid" option in your AJAX form. Just make sure that you clear values that you modify in your POST controller action form the modelstate. Otherwise HTML helpers could still use the old values:
[HttpPost]
public ActionResult Index(Win win)
{
ModelState.Remove("dealerId");
win.dealerId = "1234567890";
ModelState.Remove("posterid");
win.posterid = "chris";
ModelState.Remove("posttime");
win.posttime = DateTime.Now;
wem.addWin(win);
IEnumerable<Win> w = wem.getVenueWins(win.venue,win.windate);
return PartialView("_wingrid",w);
}
Also don't forget to include the jquery.unobtrusive-ajax.js script to your page if you want your Ajax.* helpers to work:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Ajax.ActionLink in MVC3 is getting slow after a number of requests

I have this simple MVC 3 application which simply has two controllers(Home and Edit), two actions one per controller and two views for each action,
each one of the views has an ajax action link which simply request the other view and displays the result in a div, the problem is that after a certain number of requests the page is getting slower, I checked that with fiddler and noticed that each time I press the action link the request will be send multiple times according to the equation (2 to the power n) where n is how many time the link was pressed, find below the controllers and views.
the Controllers
public class EditController : Controller
{
public ActionResult Index()
{
return View();
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Text = "Home Page";
return View();
}
}
And the views
Home View
#{
ViewBag.Title = "Home";
}
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script type="text/javascript">
function myCallback(xhr, status) {
alert(status);
}
</script>
<div id="divLoading" style="display: none">
Loading ...</div>
<div id="divResultText">
#Ajax.ActionLink("Edit Ajax", "Index", "Edit", null, new AjaxOptions
{
HttpMethod = "Get",
OnComplete = "myCallback",
UpdateTargetId = "divResultText",
LoadingElementId = "divLoading"
})
</div>
Edit View
#{
ViewBag.Title = "Edit";
}
#Ajax.ActionLink("Home", "Index", "Home", null, new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId = "divResultText",
LoadingElementId = "divLoading"
})
I have got the answer in
Ajax.ActionLink in MVC3 is getting slow after a number of requests

Resources