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

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>

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.

How to show a partial view on click of actionlink in mvc

I have the following two action links on a page:
#Html.ActionLink("User List","list");
#Html.ActionLink("Admin List","admin");
On their click I want to show/hide a partial view using jQuery. Help me with solution for this.
You could use the Ajax.ActionLink helper instead:
#Ajax.ActionLink("User List","list", new AjaxOptions { UpdateTargetId = "someDiv" });
#Ajax.ActionLink("Admin List","admin", new AjaxOptions { UpdateTargetId = "someDiv" });
This assumes that the list and admin actions return partial views:
public ActionResult List()
{
return PartialView();
}
and the result of this partial view will be injected into a DOM element with id="someDiv". Also for this to work don't forget to include the jquery.unobtrusive-ajax.js script to your page
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<div id="test"></div>
#Ajax.ActionLink("User List","list", new AjaxOptions{ UpdateTargetId = "test" });
#Ajax.ActionLink("Admin List","admin", new AjaxOptions{ UpdateTargetId = "test" });

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

Close modal window containing ASP MVC Ajax form

in a webapp I'm using an ASP MVC Ajax form in a modal window. I do not use any specific jQuery code, only some to open the modal window (i.e. showModal() function):
#Ajax.ActionLink("Open", "Add", "Home", new {id = Model.Id}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "modal", OnSuccess = "showModal()"})
This code loads my form (partial view) into a div and opens it as a modal window. In the form submit ActionResult I just use the default ModelState object to validate it, and in case of an error I return the same partial view containing model errors. This works fine except for the following situation: when the model contains no errors I want to auto-close the modal window. I tried the following:
#using (Ajax.BeginForm("Save", "Home", new AjaxOptions {HttpMethod = "POST", UpdateTargetId = "modal", OnSuccess = "hideModal(); alert('Saved');"}))
However, when the model contains errors the Ajax call is still valid, so OnSuccess will be called. I tried to solve this by sending an error HttpStatusCode in the partial view, but then the div is not updated with the new html.
I think the only solution is sending a partial view containing javascript code that closes the modal window when the model contains no errors, but this solution is not very neat in my opinion. Any other ideas?
I just had to do the same thing today. The solution I came up with was to return a JsonResult with a property set to true when the action succeeded. In the OnSuccess callback of the AjaxOptions I checked for the property and closed my modal window.
Controller Method
[HttpPost]
public ActionResult Hold(JobStatusNoteViewModel model)
{
if (ModelState.IsValid)
{
//do work
return Json(new {success = true});
}
return PartialView("JobStatusNote", model);
}
PartialView
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "JobStatusForm", OnSuccess = "closePopUp" })) { %>
<div id="JobStatusForm">
<!-- Form -->
</div>
<% } %>
<script>
function closePopUp(data) {
if (data.success) {
//close popup
}
}
</script>

problem asp.net mvc cannot load ajax content

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...
}

Resources