Submitting jquery dialog box using ajax call - jquery-ui

I'm attempting to do a search using a jquery ui dialog box, and have the results also appear in a dialog box without any redirection on the actual page. I'm thinking an easy way of doing this is just to create my ui and have a < div id > surrounding the content, then replace the div with a view using an ajax call.
I've gotten the basics of this working, but... I have no clue how to pass the input field parameters to the incoming view/controller! It's currently not using submit() in any shape or form as this causes an unavoidable page redirect afaik.
My dialog contains standard text fields such as:
#Html.HiddenFor(model => model.Id)
<label>Customer Name</label>
#Html.TextBoxFor(m => m.Name, new { #class = "text ui-widget-content ui-corner-all" })
<label>EIN</label>
#Html.TextBoxFor(m => m.Ein, new { #class = "text ui-widget-content ui-corner-all" })
<label>State Tax ID Number</label>
#Html.TextBoxFor(m => m.StateTaxId, new { #class = "text ui-widget-content ui-corner-all" })
I have a placeholder for the dialog div
<div id="dialog-searchResults" title="Search Results" class="hide">
#using (Html.BeginForm("searchResults", "Customers", FormMethod.Post, new { #id = "searchResultForm" }))
{
<div id="SearchContents">a</div>
}
</div>
The ajax call
function InsertDialogDiv(ajaxUrl, divTable) {
var jsonData = {
"id": 0
};
$.ajax({
type: 'POST',
url: BASE_URL + ajaxUrl,
data: JSON.stringify(jsonData),
success: function (data) {
$(divTable).replaceWith(data);
},
error: function (xhr, ajaxOptions, thrownError) {
$(divTable).replaceWith(xhr.responseText);
}
});
}
Where ajaxUrl='Customer/SearchResults' as the path of the view.
Replacing the div in this way does trigger the Customer's controller to hit the SearchResults function, but as I'm not submitting, the model has all null values. How do I get my precious nuggets of information?
TY & Rat's off to ya!
PS: ASP.NET C# MVC4 Razor

Related

Live search MVC

I'm looking for live search for ASP.NET and entity framework. I'm a little bit green with it. I read that it needs to use ajax, but I never used it before and can't get good example. Here is a piece of code, cshtml (part of textbox)
<div class="form-horizontal">
<hr />
<h4>Search for a client: </h4>
<div class="input-group">
<span class="input-group-addon" id="Name">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Name", "", new { #class = "form-control", placeholder = "Name" })
</div>
<div><h6></h6></div>
<div class="input-group">
<span class="input-group-addon" id="Surname">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Surname", "", new { #class = "form-control", placeholder = "Surname" })
</div>
<div><h6></h6></div>
<button type="submit" class="btn btn-default" data-toggle="modal" data-target="#infoModal">Search</button>
</div>
this is a part of controller:
public ActionResult Index(string Name, string Surname)
{
var SearchList = from m in db.Klienci
select m;
if (!String.IsNullOrEmpty(Name))
{
SearchList = SearchList.Where(s => s.Name.Contains(Name));
}
if (!String.IsNullOrEmpty(Surname))
{
SearchList = SearchList.Where(s => s.Nazwisko.Contains(Surname));
}
return View(SearchList);
}
So it search for me clients by name and surname, but it refresh full page when it lost focus or after clicking the button. How to solve it, to get live search? after each keystroke search through database? I'm a little bit green, would you Help me?
You can listen to the keyup event on your input element, read the value and send it to the server using ajax. Return the results and in the ajax call's success callback, update the ui with the results.
$(function() {
$("#Name,#SurName").keyup(function(e) {
var n = $("#Name").val();
var sn = $("#SurName").val();
$.get("/Home/Index?Name="+n+"&SurName="+sn,function(r){
//update ui with results
$("#resultsTable").html(r);
});
});
});
The code basically listens to the key up event on the two input textboxes and read the values and send to the /Home/Index action method using jquery get method asynchronously.When the action method returns the response, we update the DOM.
Assuming resultsTable is the Id of the table where we list the results.
Also, since you are returning the partial view result ( without layout headers), you should use return PartialView() instead of return View()
if(Request.IsAjaxRequest())
return PartialView(SearchList);
return View(SearchList);
Here is nice example/tutorial how to use Ajax with ASP.NET MVC
http://www.itorian.com/2013/02/jquery-ajax-get-and-post-calls-to.html
EDITED: 2016-07-20
Example:
$(function () {
$("searchField").keyup(function () {
$.ajax({
type: "POST",
url: "/Controller/Action",
data: data,
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
});
You have to visit the server to get data from server and without ajax it is not possible. Now the question is how to make ajax call, you can use jQuery js lib to do but I would recommend you to try angular as data binding in angular will fulfill your needs.
Take a look at followings links
Angular Ajax Service -
jQuery Ajax

JQuery AJAX: Update ViewModel

I have a strongly-typed MVC view that includes a form with an editor that is bound to a view model:
#model ViewModels.CommentView
#using (Ajax.BeginForm("UpdateComments", new AjaxOptions { HttpMethod="POST" }))
{
<fieldset>
<legend>Metadata</legend>
<div>
#Html.HiddenFor(model => model.Id)
<div class="editor-label">
#Html.LabelFor(model => model.Comment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Comment)
#Html.ValidationMessageFor(model => model.Comment)
</div>
</div>
<p class="action clear">
<input type="submit" value="Save" />
</p>
</fieldset>
}
When the user clicks on an element in a different part of the view, a JQuery AJAX call retrieves data from the server and updates the control:
<script type="text/javascript">
$(".load-comments").focus(function () {
var Id = $("#Id").val();
var url = "#Url.Action("GetComment")/" + Id;
$.ajax({ url: url, success: DataRetrieved, type: 'POST', dataType: 'json' });
function DataRetrieved(data) {
if (data) {
$("#Comment").val(data.Comment);
}
};
});
</script>
This functionality works as expected: the control content is visually updated. However, the value of the underlying html element is not updated, and when I post the form back to the server, the view model is empty.
How do I set the form controls' value in the JQuery function so that they post back to the server?
How did you set the HTML? ASP.NET default ModelBinder looks for id that are equals object properties to build the model back in the server. Looks like your form HTML doesnot reflect the object. Inspect each element created by Html helper and create each control as the same after comment data comes from the request. Hopes its help you! You can create a custom ModelBinder to Bind your model back in the server, take a look here: Model Biding

pass model from view to controller with html.actionlink

I am trying to get the model data from a strongly typed view to a controller.
Using the submit button is ok, I can get the data. Now I want to achieve the same with html.actionlink.
This is what I have:
View:
#model WordAutomation.Models.Document
#{
ViewBag.Title = "Document";
}
<script type="text/javascript">
$(function () {
$("#dialog").dialog();
});
</script>
<h2>Document</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Document</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ClientTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientTitle)
#Html.ValidationMessageFor(model => model.ClientTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientFullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientFullName)
#Html.ValidationMessageFor(model => model.ClientFullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientCustomSSN)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientCustomSSN)
#Html.ValidationMessageFor(model => model.ClientCustomSSN)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null, new { id = "previewLink" })
</div>
<div id="dialogcontainer">
<div id="dialogcontent"><input type="submit" value="Create" /> </div>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function() {
$("#dialogcontainer").dialog({
width: 400,
autoOpen:false,
resizable: false,
title: 'Test dialog',
open: function (event, ui) {
$("#dialogcontent").load("#Url.Action("PreviewWordDocument", "Home")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$("#previewLink").click(function(e) {
e.preventDefault();
$("#dialogcontainer").dialog('open');
});
});
</script>
}
Controller:
public ActionResult Document()
{
return View();
}
[HttpPost]
public ActionResult Document(WordAutomation.Models.Document model)
{
Models.Utility.EditWord word = new Models.Utility.EditWord();
word.EditWordDoc(model);
return View("Display", model);
}
public ActionResult PreviewWordDocument()
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
The document actionresult can get the model, but I want to know how can I get the values from the actionlink which will trigger the PreviewWordDocument action.
Thanks in advance, Laziale
The form can only be posted using the submit button to the URL given by its action attribute.
You can however send the form data to a different URL using the jQuery post method, manually validating the form before it is sent.
That way you can send the form data to the PreviewWordDocument controller method and handle the response in order to show the preview in the desired div.
(It will be helpful if you give an id to the form, so you can easily find it using jQuery)
So your click event handler for the preview link will look like this:
$("#previewLink").click(function(e) {
e.preventDefault();
if($("#YourFormId").valid()){
$("#dialogcontainer").dialog('open');
}
});
In the open function of the dialog you will post the form (which was already validated) to the preview controller method, using the jQuery ajax function. The response will be loaded into the dialogContent div:
$.ajax({
type: "POST",
url: $("#previewLink").attr("href"), //the preview controller method
data: $("#YourFormId").serialize(),
success: function (data) {
//load ajax response into the dialogContent div
$("#dialogcontent").html(data);
},
error: function(xhr, error) {
$("#YourFormId").prepend('<div id="ajaxErrors"></div>')
.html(xhr.responseText);
}
});
Now you will now be able to receive the whole document in the PreviewWordDocument action:
public ActionResult PreviewWordDocument(WordAutomation.Models.Document model)
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
in a HTML page when you click on a submit button all the input elements inside the form which the submit button resides in will posted to server, but when you click on a anchor (<a> tag ). you only send a request with a Get method and without posting any value.but if you want to send particular value to the server with this approach you can do it by query string.you have used following to make a request :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null,
new { id = "previewLink" })
this will produce :
<a id="previewLink" href="/Home/PreviewWordDocument"> Preview </a>
which is incorrect.to pass any value to the server with ActionLink use 4th parameter like this :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home",
new { id = "previewLink" }, null)
the result from this code would be :
Preview
cheers!

How to pass selected dropdownlist value to Ajax.ActionLink in MVC 4?

I am trying to pass a Form value "CustomerID" (i.e.dropdownlist selected value) using Ajax.Actionlink in MVC 4. Can someone tell me what I am doing wrong here?
<div class="editor-label">
#Html.LabelFor(model => model.CustomerID, "Customer Name")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.CustomerID, Model.CustomersList, "-- Select --")
#Html.ValidationMessageFor(model => model.CustomerID)
</div>
<div id="ApptsForSelectedDate">
#Ajax.ActionLink("Click here to view appointments",
"AppointmentsList",
new {id = Model.CustomerID},
new AjaxOptions
{
UpdateTargetId = "ApptsForSelectedDate",
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "progress"
}
)
</div>
<div id="progress">
<img src="../../Images/ajax-loader.gif" alt="loader image" />
</div>
My controller method looks like this:
public PartialViewResult AppointmentsList(int id)
{ ... }
You should use an Ajax.BeginForm and put the dropdown inside the form. This way the value will be automatically passed.
Unfortunately since you cannot nest html forms if you already have another form wrapping this markup you cannot use a nested form.
In this case you could use a normal link:
#Html.ActionLink(
"Click here to view appointments",
"AppointmentsList",
null,
new { id = "applink" }
)
and in a separate javascript file AJAXify it and append the necessary information to the query string by reading the selected dropdown value at the moment the AJAX request is sent:
$(function() {
$('#applink').click(function() {
$('#progress').show();
$.ajax({
url: this.href,
type: 'GET',
data: { id: $('#CustomerID').val() },
complete: function() {
$('#progress').hide();
},
success: function(result) {
$('#ApptsForSelectedDate').html(result);
}
});
return false;
});
});

MVC3 using jquery.validate.unobtrusive.js and $("#form").submit() hijax not working

I have a basic form
#Html.ValidationSummary(true)
using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #class = "form" }))
{
<div class="editor-label">
<label for="Name">#Html.LabelFor(model => model.Name)</label>
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
</div>
and so on. My Model is using data annotations and validation is turned on.
I'm hijaxing the form using some jquery:
<script type="text/javascript">
$("form[action='/']").submit(function () {
$.post($(this).attr("action"), $(this).serialize(), function (response) {
$("#contactForm").replaceWith($("#contactForm", response));
});
return false;
});
</script>
This works if I type the fields in correctly and submit. But the strange thing is if I enter an invalid value into one of the form fields and the validation code kicks in to highlight my mistake the submit event function I appended in the hijaxing script above is lost and a full post happens.
Any good ideas as to how I get around this?
I think when you add a submit handler to your form you are overwriting the submit handler that the jquery validation / data annotations adds.
To get around this you can add:
var theForm = $(this);
if ( theForm.valid() ) {
$.post($(this).attr("action"), $(this).serialize(), function (response) {
$("#contactForm").replaceWith($("#contactForm", response));
});
return false;
}
This will make sure the form is valid before making the POST.

Resources