Return PartialView to specific div from Action - ajax

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

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.

Redirecting to ajax edit form on model binding error in asp.net mvc

I have a simple model called JobStatus, and I am enabling edit functionality within the Index view with an Ajax Actionlink.
My problem is that if there is a model error when editing an item, I don't know how to bring the item back to the model.
My Index action in my controller:
public ActionResult Index()
{
return View(db.JobStatuses.OrderBy(x => x.JobStatusID).ToList());
}
Here is my Index view:
#model IEnumerable<Project.Models.JobStatus>
#foreach (var item in Model)
{
<div id='#string.Format("div_{0}", item.JobStatusID)'>
#item.JobStatusID
#item.Name
#item.Description
#Ajax.ActionLink("Edit", "Edit", new { id = item.JobStatusID }, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = string.Format("div_{0}", item.JobStatusID) })
</div>
}
And here is my edit GET request:
public ActionResult Edit(string id = null)
{
JobStatus jobstatus = db.JobStatuses.Find(id);
if (jobstatus == null)
{
return HttpNotFound();
}
return PartialView(jobstatus);
}
My edit.cshtml:
#model Project.Models.JobStatus
#using Microsoft.Ajax;
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.JobStatusID)
#Html.TextBoxFor(model => model.Name, null, new { #class = "form-control" })
#Html.TextBoxFor(model => model.Description, null, new { #class = "form-control" })
<input type="submit" value="Save" />
}
And finally my edit POST method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(JobStatus jobstatus, string action)
{
if (ModelState.IsValid)
{
db.Entry(jobstatus).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
// Not sure what to do here, how to I repopulate my index form?
return RedirectToAction("Index");
}
At the moment, on a modelstate failure the user is just redirected to the index page - what I'd like is to simply redisplay the index form, with the appropriate edit form enabled and populated, and any validation errors shown.
I've tried redirecting to my Edit action, but this just shows my form on a new page, without my index form (because currently my edit action is an ajax action)
Of course, please let me know if there is a better way to achieve this!
You can't do the RedirectToAction with Ajax Post.
Check out asp.net mvc ajax post - redirecttoaction not working
But you can load in the following way
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Edit(JobStatus jobstatus, string action)
{
if (ModelState.IsValid)
{
db.Entry(jobstatus).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return Json(new{id=jobStatus, success=true})
}
Once you get the JSON result from server you can load the same using the id returned
Like
$.post('/jobs/edit',{data:$(form).serialize()},function(data){
if(data.success){
$.get('/jobs/index/'+data.id,{},function(data){
$('#container').html(data);
});
}
});

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/

The error of can not find View in Ajax form

I ask a similar question here
So I add Some OnComplete Functions and Id to Ajax Forms, And there is:
This is My View:
#foreach(var item in Model) {
<tr id="TR#(item.Id)">
#{Html.RenderPartial("_PhoneRow", item);}
</tr>
}
_PhoneRow:
#model PhoneModel
#using(Ajax.BeginForm("EditPhone", new { id = Model.Id }, new AjaxOptions {
UpdateTargetId = "TR" + Model.Id,
OnComplete = "OnCompleteEditPhone"
}, new { id = "EditAjaxForm" + Model.Id})) {
<td>#Html.DisplayFor(modelItem => Model.PhoneNumber)</td>
<td>#Html.DisplayFor(modelItem => Model.PhoneKind)</td>
<td><input type="submit" value="Edit" class="CallEditPhone" id="edit#(Model.Id)" /></td>
}
Controller:
public ActionResult EditPhone(long Id) {
//Get model by id
return PartialView("_EditPhoneRow", model);
}
public ActionResult SavePhone(PhoneModel model) {
//Save Phone, and Get Updatet model
return PartialView("_PhoneRow", model);
}
_EditPhoneRow
#model PhoneModel
#using(Ajax.BeginForm("SavePhone", new { id = Model.Id }, new AjaxOptions {
UpdateTargetId = "TR" + Model.Id,
OnComplete = "OnCompleteSavePhone"
})) {
<td>#Html.EditorFor(modelItem => Model.PhoneNumber)</td>
<td>#Html.EditorFor(modelItem => Model.PhoneKind)</td>
<td><input type="submit" value="Save" class="SaveEditPhone" id="save#(Model.Id)" /></td>
}
And Oncomplete Scripts:
function OnCompleteEditPhone() {
$('input.SaveEditPhone').click(function () {
var id = $(this).attr("id").substring(4);
$('form#SaveAjaxForm' + id).trigger('submit');
});
}
function OnCompleteSavePhone() {
$('input.CallEditPhone').click(function () {
var id = $(this).attr("id").substring(4);
$('form#EditAjaxForm' + id).trigger('submit');
});
}
So Click Edit Worked perfect, Then Click Save Worked good also, But in second time when i click the Edit Button I have an Error in Post Action I copy the Firebug console here:
http://Mysite/members/editphone/7652 200 OK 582ms
http://Mysite/members/savephone/7652 200 OK 73ms
http://Mysite/members/editphone/7652 500 internal server error 136ms
<title>The view 'EditPhone' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...
So where is the problem? If I remove OnCompleteSavePhone The Edit button for second time not worked, and with this function I have an error that not make any sense, How Can I fix it? I actually load partial views by Ajax, And need the buttons of this views worked correctly, at first every thing is fine but after Ajax result They don't, I think to add some Oncomplete functions, but there is an error also.
Your previous question is answered now. You had broken markup. As a consequence of this you no longer need to care about any OnComplete events and doing some auto triggers, form submissions and stuff. This will be handled by the Ajax.BeginForm infrastructure automatically for you.

Editor templates/BeginForm does not update the values after returning from action but while debugging i see the data

#using (Ajax.BeginForm("SaveItemAndProperties", "HomeBuilder",
new AjaxOptions
{
UpdateTargetId = "divSaveItemAndProps",
InsertionMode = InsertionMode.Replace
}))
{
#Html.EditorForModel()
<input type="submit" value="Submit" />
}
In Model which is called from EditorForModel
#Html.EditorFor(m => m.PropertyValues)
PropertyValues is a list of properties and is a calling a EditorTemplate.
From the Action I change the value and then try to update the data back to the View
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public PartialViewResult SaveItemAndProperties(PropertyBuilderViewModel modelValues)
{
//Change on property in modelValues
return PartialView("PropertyBuilderControl", modelmodelValues);
}
When i am debugging i see the data propertly but it does not display in the view.
Any idea why it is doing so.
What are you changing in your action? HTML helpers such as TextBoxFor, HiddenFor, DropDownListFor, CheckBoxFor, ... first look at ModelState when binding and after that in the model. So if in your controller action you intend to do something like this:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public PartialViewResult SaveItemAndProperties(PropertyBuilderViewModel modelValues)
{
modelValues.Foo = "some new value";
return PartialView("PropertyBuilderControl", modelmodelValues);
}
make sure you remove that value from the model state or you won't see any updates once you render the view again:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public PartialViewResult SaveItemAndProperties(PropertyBuilderViewModel modelValues)
{
ModelState.Remove("Foo");
modelValues.Foo = "some new value";
return PartialView("PropertyBuilderControl", modelmodelValues);
}

Resources