ASP.NET MVC: OnKeyUp event for Ajax - ajax

When I wanna use the OnKeyUp event with AJAX in ASP.NET I have to do:
#using(Ajax.BeginForm("Action", "Controller", new AjaxOptions{... UpdateTargetId = "target"}) {
<div id = "target"></div>
#Html.TextBox ("TextField","", new {#OnKeyUp = "TriggerFunction()"}
<input type="submit" id = "button" style = "display:none"/>
}
Then in JQuery
function TriggerFunction(){
$("#button").trigger("click")
}
Although this works, I'm curious does ASP.NET MVC have any built in feature to do this? I mean trigger the BeginForm method based on different events like OnKeyUp or OnChanged?

Related

MVC5 Ajax Call using Controller

I am trying to update my Razor view content using ajax in ASP.Net MVC 5. But, everytime its loading total page instead of partial request to the controller.
Please help which resources i need to add to my prject to work with ajax in MVC5 speciafically.
Resources Attched to my project to use Ajax:
jquery.unobtrusive-ajax.min.js
View Design:
#using (Ajax.BeginForm("RoomsAvail", "Bookings", new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId ="RoomsAvailData",
}))
{
<div class="col-sm-4 paddingzero margintopclass">
<button type="submit" value="Search">
<img src="~/Content/images/search.png" style="cursor:pointer" alt="Search" />
</button>
</div>
}
Booking Controller Action method
public ActionResult RoomsAvail(FormCollection inputParams)
{
minRatesInventory="Some Model Data from DB";
if(Request.IsAjaxRequest())
{
return PartialView("", minRatesInventory);
}
return View(minRatesInventory);
}
In the above code snippet, Request.IsAjaxRequest() is always returning false.
EDIT
I have added jquery.unobtrusive-ajax.min.js before jQuery. It makes problem to call ajax. I have updated this and its working fine.

Update partial view after edit

I have the following index:
<div id='addProduct'>
#{ Html.RenderPartial("Create", new BoringStore.Models.Product()); }
</div>
<div id='productList'>
#{ Html.RenderPartial("ProductListControl", Model.Products); }
</div>
The partial Create view contains an invisible div which is used to create a new product.
After doing so the partial view ProductListControl is updated.
Now I want to do so with an edit function.
Problem: It's not possible to integrate the edit page while loading the index because at this moment I don't know which product the user wants to edit.
My thought:
I'd like to call my existing edit view in an jquery modal (not the problem) so the user can perform changes.
After saving the modal is closed (still not the problem- I could handle this) and the ProductListControl is updated (here's my problem ... :().
How am I able to do so?
I've seen some tutorials but I'd like to keep it as clean & easy as possible.
Most of them are using dom manipulating and get feedback from the server (controller) by a JsonResult.
If possible I'd like to stick to the razor syntax, no pure JavaScript or jquery and if possible I'd like to avoid JsonResults.
One way might be to use the Ajax.BeginForm for your create product view.
The Ajax.BeginForm accepts a number of AjaxOptions, one being the UpdateTargetId (your DOM id, in this case your productlist div), more info here.
Then in your product controller code you can return a partial view, with the product list. So for example:
Index.cshtml
#using (Ajax.BeginForm("AjaxSave", "Product", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "productList", InsertionMode = InsertionMode.Replace }))
{
// your form
<p>
<input type="submit" value="Save" />
</p>
}
...
<div id="productList">...
</div>
ProductController.cs
[HttpGet]
public ActionResult AjaxSave(Product product)
{
if (ModelState.IsValid)
{
// save products etc..
}
var allProducts = _productService.GetAllProducts();
return PartialView("ProductListControl", allProducts);
}
There is a nice article on about this here.

ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor does not reflect changes done on the server

I'm using the Ajax.BeginForm helper in ASP.NET MVC3 to submit a form that replaces itself with new values in the form set on the server. However when I use helpers like Html.TextBoxFor I get the values that was submitted, not the values I inserted into the model on the server.
For example; I set SomeValue to 4 in my action and show it in a textbox. I change the value to 8, hit submit and would expect the value to be changed back to 4 in the textbox, but for some reason it stays 8. But if I output SomeValue without using Html helpers it says 4. Anybody have some clue about what is going on?
My controller:
public ActionResult Index(HomeModel model)
{
model.SomeValue = 4;
if (Request.IsAjaxRequest())
return PartialView(model);
return View(model);
}
public class HomeModel
{
public int? SomeValue { get; set; }
}
My View (please not that I have all the needed javascript in my layout page):
<div id="ajaxtest">
#using(Ajax.BeginForm(new AjaxOptions{ InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ajaxtest", HttpMethod = "Post" })) {
#Html.TextBoxFor(model => model.SomeValue)
<input type="submit" value="Update" />
}
</div>
you can use
ModelState.Clear()
in your controller method to make the html helpers use your changed model. Otherwise they use the values from the form submit
Have a look at: Asp.net MVC ModelState.Clear
in your POST method you need to do
ModelState.Clear();
to reflect the changes made after the post

ASP.Net MVC 3 validation on AjaxForm

I have an ajax form on razor view engine. For validation i use dataanotation classes. Validation work fine when user submit the form, validation messages work fine.
The problem is, validation wont work on keyup or blur events.
How can i activate validation without submit on ajaxform(ajax.beginform)
Here is my view code:
#using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace,
UpdateTargetId = "employeeDetail", HttpMethod = "Post", OnComplete = "Complete",
Confirm = "Confirm?" }))
{
#Html.TextBoxFor(model => model.Email)
#Html.ValidationMessageFor(model=>model.Email)
<span style="float:right"><input type="submit" class="tableGenelButton" id="submitButton" value="Kaydet" /></span>
}
Model:
[RequiredWithMessage]
[Display(Name = "E-Mail")]
public string Email { get; set; }
Update:
Ok, apparently you're using Ajax.BeginForm which uses MicrosoftAjax in stead of jQuery (I didn't realize that before). This one needs some extra work to enable client side validation:
You need
<% Html.EnableClientValidation(); %>
Somewhere in your page, and also links to MicrosoftAjax.js, MicrosoftMvcAjax.js and MicrosoftMvcValidation.js
Here's a link that might be interesting for you:
ASP.NET MVC Client Side Validation With Ajax.BeginForm
To enable client side validation for a custom validation attribute (I guess [RequiredWithMessage] is one of those), you have to implement the IClientValidatable interface.
Here is an article that explains how to do that:
The Complete Guide To Validation In ASP.NET MVC 3 - Part 2
Assuming you have client side validation enabled, you will need to call .validate() in the relevant events:
$("#theFormToValidate input").blur(function(){
$("#theFormToValidate").validate();
});
and
$("#theFormToValidate input").keyup(function(){
$("#theFormToValidate").validate();
});

jQuery Validation Problem using MVC 3

My problem is I am using the MVC3's feature of unobtrusive client side validation but I need to hook into it and add a function that fires on a successful validation but before the form is posted.
I'm hoping there is some pre-built helper or an easy way to hook into the validator.
Here's a code snippet:
#using (Html.BeginForm("MyAction","MyController")) {
#Html.ValidationSummary(true)
<fieldset> <legend><legend>
<label for="FirstName">First Name</label>
#Html.TextBoxFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
try these articles...
http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
Is it possible to "hack into" the unobtrusive validaton supported in ASP.NET MVC 3?
hope these help you ...
thanks
I ended up needing to hook into the validation process to perform my own custom validation and also do some div collapsing. Here's a snippet of jQuery that accomplished what I needed:
//Hijack the submit event to do custom validation and collapse the div
$('#theFormName').submit(function () {
var customErrorHandling = false;
//do some custom validation
if (customerErrorHandling == false) {
//Now do the jQuery validation
if ($('#theFormName').valid()) {
//do some div collapsing
$('#theFormName').unbind('submit');
$('#theFormName').submit();
}
}
return false;
});

Resources