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

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.

Related

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/

Return PartialView to specific div from Action

I am playing about with jQuery UI and PartialViews and have run into a problem I can't quiet get my head around.
This bit works as I expect:
<div>
#Ajax.ActionLink("Test Me!", "dialogtest", new { id = Model.Id }, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "dialogtest-view" })</td>
</div>
<div id="dialogtest-view">
</div>
this GETs to this action method
[HttpGet]
public PartialViewResult DialogTest(int id)
{
//pretend to get something from DB here
var vm = new DialogUITestVM();
return PartialView("uidialog_partial", vm);
}
And returns me a PartialView which displays in the targeted div. jQuery + jQueryUI is used to pop this div up as a modal dialog. Part 1 of test done!
OK so now let's say the PartialView returned is just a basic form with a textbox, something along the lines of:
#using (Html.BeginForm("DialogTest", "pages", FormMethod.Post))
{
#Html.HiddenFor(x => x.Id)
#Html.TextBoxFor(x => x.Name)
<button type="submit">Test Me!</button>
}
This is POSTd back to the controller fine -
[HttpPost]
public ActionResult DialogTest(DialogUITestVM vm)
{
//arbitrary validation so I can test pass and fail)
if (vm.Name.Equals("Rob"))
{
//error!
vm.ErrorMessage = "There was an error you numpty. Sort it out.";
return PartialView(vm);
}
//hooray it passed - go back to index
return RedirectToAction("index");
}
However - if I make the action fail the validation, rather than targeting the PartialView to the div again, it redraws the whole page (which obviously loses the jQuery UI dialog).
What I want is: if validation fails, just update the div that contained the form.
Where am I going wrong?
You could use an Ajax form in your partial instead of a normal form and use a OnSuccess callback in your AjaxOptions:
#using (Ajax.BeginForm("DialogTest", "pages", new AjaxOptions { UpdateTargetId = "dialogtest-view", OnSuccess = "success" }))
{
#Html.HiddenFor(x => x.Id)
#Html.TextBoxFor(x => x.Name)
<button type="submit">Test Me!</button>
}
and then modify your controller action respectively:
[HttpPost]
public ActionResult DialogTest(DialogUITestVM vm)
{
//arbitrary validation so I can test pass and fail)
if (vm.Name.Equals("Rob"))
{
//error!
vm.ErrorMessage = "There was an error you numpty. Sort it out.";
return PartialView(vm);
}
//hooray it passed - go back to index
return Json(new { redirectUrl = Url.Action("Index") });
}
and of course define the corresponding success callback in your javascript files:
function success(result) {
if (result.redirectUrl) {
window.location.href = result.redirectUrl;
}
}

mvc3 how do I clear the submitted form values

I am new to asp .net mvc3. I am trying to create a failrly simple blog comments section.
I have a CommentsViewModel
public class CommentsViewModel
{
public CommentModel NewComment { get; set; }
public IList<CommentModel> CommentsList { get; set; }
}
The corresponding view is like
<div id="CommentsArea">
#Html.Partial("CommentsList", Model.CommentsList)
</div>
#using (Ajax.BeginForm("Create",
"Comment",
new { id = Model.NewComment.detailsId, comment = Model.NewComment },
new AjaxOptions { UpdateTargetId = "CommentsArea" ,
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace}))
{
<div class="display-label">Add Comment</div>
<div class="display-field">
#Html.EditorFor(model => Model.NewComment.Body)
</div>
<input type="submit" value="Post" />
}
Now when user enters Post button I want the "CommentsArea" to be updated with the new comments list and also the form values to be cleared with empty text.
Here is the Post method:
[HttpPost]
public ActionResult Create(int id, CommentModel newcomment)
{
var newsItem = m_db.NewsList.Single(news => news.Id == id);
if (!string.IsNullOrWhiteSpace(newcomment.Body))
{
newcomment.detailsId = id;
newsItem.Comments.Add(newcomment);
m_db.SaveChanges();
}
return PartialView("CommentsList", newsItem.Comments);
}
Now when user clicks Post button the list gets updated properly,
but the form values are not cleared. i.e. if I posted a comment "New Comments", the comments list gets updated with "New Comments", but that text remains inside the edit box of the form.
How do I clear that text?
just call a js function on success of form submit.
#using (Ajax.BeginForm("Create",
"Comment",
new { id = Model.NewComment.detailsId, comment = Model.NewComment },
new AjaxOptions { OnSuccess="ClearInput", HttpMethod = "Post",}))
on js function render create view again
function ClearInput(){
//call action for render create view
$.ajax({})
}

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