I have a view within a MS MVC [razor] project where I want to submit view data back to a controller via a JSON post operation. I have looked around and I cannot find how to retrieve and package the view data for submission back to the controller. I was under the assumption that the JSON serialize operation would package the data when called but this does not seem to be happening. For example:
MVC View ------------------------------
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<center>
<fieldset id="UserCreateFieldset">
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<p>
<input type="button" name="CreateButton" value="Create" onclick="CreateUser()" />
</p>
</fieldset>
</center>
}
<script>
function CreateUser()
{
var infoForm = $("#UserCreateFieldset");
var entries = infoForm.serializer.Serialize(Model);
$.ajax(
{
url: '#Url.Action("CreateUser", "User")',
data: entries,
type: "POST",
dataType: "json",
success: function (data)
{
$.event.trigger({
type: "CreateUserCompleted",
NewUserID: 1,
});
}
});
}
</script>
Just to note; when the controller is called via the post it receives back the model -- but it contains the original values used to load the view.
Peter
Use the .serialize() method from jquery:
function CreateUser()
{
var data = $('form').serialize();
$.ajax({
url: '#Url.Action("CreateUser", "User")',
data: data,
type: "POST",
dataType: "json",
success: function (data)
{
$.event.trigger({
type: "CreateUserCompleted",
NewUserID: 1,
});
}
});
}
You can instead of using Html.BeginForm use Ajax.BeginForm to not mess with the internals if you are doing the same thing as a the Html.BeginForm without anything special. you could change your code to:
#using(Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
HttpMethod = "POST"
}))
{
// Same form
}
It even has OnSuccess method which can be used in the AjaxOptions declaration:
#using(Ajax.BeginForm("MyAction", "MyController",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "TriggerEvent"
}))
{
// Same form
}
And you set a function in the javascript to be called on success:
function TriggerEvent() {
$.event.trigger({
type: "CreateUserCompleted",
NewUserID: 1,
});
}
Related
My partial view which is loaded into a bootstrap partial on my Index page, should be posting type Announcement but is posting type AnnouncementViewModel of the Index page model to the Create controller.
The #modal-container is specified in my _Layout, which is working as expected.
Unsure about the controllers - they appear correct, the problem is stemming from my ajax post I believe but I don't know what's the issue. I get the error after POST, however the database does update with the model correctly, but afterwards I get the below error.
I have specified $('#create-container')/$('form') as the form in which to serialize and send back to the controller.
Why is it doing this?
Error:
The model item passed into the dictionary is of type 'AnnouncementsViewModel', but this dictionary requires a model item of type 'Announcement'.
Index:
#model AnnouncementsViewModel
<h2>Announcements</h2>
<div>
#Html.ActionLink("Create", "Create", "Announcements", null, new { #class = "modal-link btn btn-sm" })
<div class="announcementTable">
<div id="announcementList">
#{Html.RenderPartial("List", Model.AnnouncementList);}
</div>
</div>
</div>
Partial:
#model Announcement
#section Scripts {
<script type="text/javascript">
$(function () {
$('#btn-create').click(function () {
$.ajax({
url: '#Url.Action("Create","Announcements")',
type: 'POST',
contentType: 'application/json',
data: $('#create-container').serialize(),
success: function (data) {
if (data.success == true) {
$('#modal-container').modal('hide');
location.reload(false)
} else {
$('#modal-container').html(data);
}
}
})
});
$('#btn-close').click(function () {
$('#modal-container').modal('hide');
});
});
</script>
}
<div class="create-container">
#using (Html.BeginForm())
{
<div class="newAnnouncementTableRow1">
<div>#Html.LabelFor(m => m.Title)</div>
<div>#Html.EditorFor(m => m.Title)</div>
<div>#Html.LabelFor(m => m.Details)</div>
<div>#Html.EditorFor(m => m.Details)</div>
</div>
<div class="newAnnouncementTableRow2">
<div>#Html.LabelFor(m => m.StartDT)</div>
<div>#Html.EditorFor(m => m.StartDT)</div>
<div>#Html.LabelFor(m => m.ExpiryDT)</div>
<div>#Html.EditorFor(m => m.ExpiryDT)</div>
<div>#Html.LabelFor(m => m.Enabled)</div>
<div>
#Html.RadioButtonFor(m => m.Enabled, 1)Yes
#Html.RadioButtonFor(m => m.Enabled, 0, new { #checked = "checked" })No
</div>
</div>
<div>
<button type="submit" id="btn-create" class="btn btn-sm">Save</button>
<button type="button" class="btn btn-default modal-close-btn" data-dissmiss="modal">Cancel</button>
</div>
}
</div>
Controller:
[HttpGet]
public ActionResult Index()
{
var avm = new AnnouncementsViewModel
{
AnnouncementList = new List<Announcement>()
};
avm.AnnouncementList = GetAnnouncementList();
return View(avm);
}
[HttpGet]
public ActionResult Create()
{
return PartialView("Create");
}
[HttpPost]
public ActionResult Create(Announcement a)
{
db.DbAnnouncement.Add(a);
db.SaveChanges();
return Index();
}
You set contentType: 'application/json' it your .ajax() call but returning View from Controller. Either change contentType to html or change controller to return JsonResult and return Json("yourData");
I recommend you to change your ajax call:
$.ajax({
/* other data */
dataType : "html",
contentType: "application/json; charset=utf-8",
/* other data */
success: function (data) {
$('#modal-container').modal('hide');
location.reload(false)
},
error: function (jqXHR, textStatus, errorThrown )
{
$('#modal-container').html(data);
}
/* other data */
});
Thing is response from server in your case always success but it returns html rather than json so you just don't have data.success at all.
The other issue as mentioned in the comments was that the controller was redirecting to an action method that it could not.
Changing return Index(); to return RedirectToAction("Index", "Announcements"); solved the error and the redirecting to the Create partial page caused by using return View();.
After much of struggle im posing this question. Im using a Kendo Upload on a page. Am able to post the selected files on the asyn mode with whe the page has Html.BeginForm. But I'm not able to send file details as HttpPostedFileBase when I use ajax request to send data to the controller.
Following is my html
<form class="form-horizontal" role="form">
<div class="form-group">
#Html.Label("Complaint Name", new { #class = "col-sm-3 control-label" })
<div class="col-sm-4">
#Html.TextBoxFor(
m => m.ComplaintName,
new
{
#TabIndex = "1",
#class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
#Html.Label("Complaint Details", new { #class = "col-sm-3 control-label" })
<div class="col-sm-4">
#Html.TextBoxFor(
m => m.ComplaintDetails,
new
{
#TabIndex = "2",
#class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
#Html.Label("Choose files to upload", new { #class = "col-sm-3 control-label" })
<div class="col-sm-9 nopaddingforTextArea">
<input name="files" id="files" type="file" />
</div>
</div>
<div class="form-group">
<div>
<input id="btnSubmit" class="btn btn-primary pull-right" type="button" />
</div>
</div>
</form>
Following is my action
public ActionResult SaveComplaintDetails(string complaintName, string complaintDetails, IEnumerable<HttpPostedFileBase> files)
{
}
Following is my js
$("#files").kendoUpload({
async: {
saveUrl: '#Url.Action("EsuperfundCommentsBind", ClientInboxConstants.NewQuery)',
autoUpload: false
},
multiple: true
});
$("#btnSubmit").click(function () {
//Ajax call from the server side
$.ajax({
//The Url action is for the Method FilterTable and the Controller PensionApplicationList
url: '#Url.Action("SaveComplaintDetails", "Complaints")',
//The text from the drop down and the corresponding flag are passed.
//Flag represents the Index of the value in the dropdown
data: {
complaintName: document.getElementById("ComplaintName").value,
complaintDetails: document.getElementById("ComplaintDetails").value,
files: //What to pass here??
},
contentType: "application/json; charset=utf-8",
//Json data
datatype: 'json',
//Specify if the method is GET or POST
type: 'GET',
//Error function gets called if there is an error in the ajax request
error: function () {
},
//Gets called on success of the Ajax Call
success: function (data) {
}
});
});
My question is how to pass the selected files in Kendo Upload in ajax as a parameter?
Any help in this aspect would be really appreciated.
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using:
<script>
var formdata = new FormData($('form').get(0));
</script>
This will also include any files generated with: <input type="file" name="myImage" .../> and post it back using:
<script>
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
</script>
and in your controller:
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model,
HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
<script>
formdata.append('someProperty', 'SomeValue');
</script>
**Example Usage :**
View :
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
data: formdata,
dataType: "json",
processData: false,
contentType: false,
success: function (response) {
//code omitted for brevity
}
});
});
});
</script>
*Controller :*
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//code omitted for brevity
return Json(new { success = false, message = "Max. file size 10MB" }, JsonRequestBehavior.AllowGet);
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#createDetail').get(0));
$.ajax(
{
type: 'POST',
url: '#Url.Action("Detail_Create", "Product")',
data: formdata,
processData: false,
success: function (result) {
if (result.success == false) {
$("#divErr").html(result.responseText);
} else {
parent.$('#CreateWindowDetail').data('kendoWindow').close();
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#divErr").html(xhr.responseText);
}
});
});
});
#using (Html.BeginForm("Detail_Create", "Product", FormMethod.Post, new { id = "createDetail", enctype="multipart/form-data"}))
{
<div id="divErr" class="validation-summary-errors"></div>
<fieldset>
<ol>
<li>
#Html.LabelFor(m => m.Price)
#(Html.Kendo().NumericTextBoxFor(m => m.Price).Name("Price").Format("{0:0}")
.HtmlAttributes(new { style = "width:100%" })
)
</li>
<li>
#Html.LabelFor(m => m.Description)
#Html.TextBoxFor(model => model.Description, new { #class = "k-textbox", id = "Description", style = "width:100%;" })
</li>
<li>
#Html.LabelFor(m => m.Group)
#(Html.Kendo().ComboBox()
.Name("Group")
.Placeholder("Введите группу детали")
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { style = "width:100%;" })
.Filter("contains")
.MinLength(1)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Group_Read_ComboBox", "Product");
})
.ServerFiltering(true);
})
)
</li>
<li>
#Html.LabelFor(m => m.Image)
#(Html.Kendo().Upload()
.Name("files")
)
</li>
</ol>
</fieldset>
<button type="submit" id="get" class="k-button">Добавить</button>
}
[HttpPost]
public ActionResult Detail_Create(DetailModel model, IEnumerable<HttpPostedFileBase> files)
{
string error = string.Empty;
if (ModelState.IsValid)
{
.....
}
IEnumerable<System.Web.Mvc.ModelError> modelerrors = ModelState.SelectMany(r => r.Value.Errors);
foreach (var modelerror in modelerrors)
{
error += "• " + modelerror.ErrorMessage + "<br>";
}
return Json(new { success = false, responseText = error }, JsonRequestBehavior.AllowGet);
}
after pressing the button, the controller null comes to how to fix. 2 days already sitting, and the time comes to an end
I have a very simple view and can't figure out why my textbox value is not passing to my controller. Will the actionlink work for providing the controller the parameter?
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("LookupEmployee", "Home")) {
<div class="jumbotron">
<h2>Personnel System</h2><br />
<p>ID: <input type="text" id=employeeID name="employeeID" /></p>
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null, new { #class = "btn btn-primary btn-large" })
</div>
}
<div class="row">
</div>
My HomeController takes the parameter and fills the dataset. I have hard coded a value and verified that this code works:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LeaveBalance(string employeeID)
{
//ViewBag.Message = "Your application description page.";
if (!String.IsNullOrEmpty(employeeID))
{
DataSet gotData;
LeaveRequestWCF myDataModel = new LeaveRequestWCF();
gotData = myDataModel.GetTheData(Convert.ToInt32(employeeID));
myDataModel.theModelSet = gotData;
return View(myDataModel);
}
return View();
}
}
Any advice? As you can tell, I'm new with MVC and trying to drift away from web forms.
OPTION 1:
You are using Html.ActionLink to post a form, which cannot be done because Html.ActionLinks are rendered as Anchor tags. Anchor tags make GET Requests unless we explicitly handle their JQuery click event. Use a Submit button to post a form for an appropriate controller action. So instead of -
#Html.ActionLink("Your Leave Balance", "LeaveBalance", "Home", null,
new { #class = "btn btn-primary btn-large" })
go for -
<input type="submit" class="SomeClass" value="Submit" />
OPTION 2:
You can also use AJAX POST using JQuery click event for anchor tag to post the form and once you get the result, you can make a client side redirection.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("#solTitle a").click(function() {
var data = {
"Id": $("#TextId").val()
};
$.ajax({
type: "POST",
url: "http://localhost:23133/api/values",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
// handle redirection here
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
ActionLink creates a simple <a href /> on the page, that will send a get request to the server.
You need a submit button instead, so your form gets posted with its form inputs. Use:
<button type="submit">Your Leave Balance</button>
I am working with Asp.Net MVC4, I need to retrieve the date and time from the server and not the client. To restore them when I must click a button in the view, for example the name of the button "Nuevo" and from the view so I defined, the event is called by javascript in Action define the controller (Home) and ActionResult (Nuevo):
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ }),
success: function () {}
});
}
</script>
On receipt the data controller in the New ActionResult as follows:
[HttpPost]
public ActionResult Nuevo()
{
Persona persona = new Persona();
persona.Fecha = DateTime.Now;
persona.Hora = DateTime.Now;
return View(persona);
}
This is my view, I use typed views:
#model MvcJavaScript.Models.Persona
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({}),
success: function (data) {
}
});
}
</script>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { sololectura = true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { sololectura = true })</td>
</tr>
</tbody>
</table>
}
What I need to do is to insert a new record (by clicking on the button "Nuevo") I load the default server time and date in different textbox.
Running this example enters the New ActionResult but to return to the data to view the TextBox is void, I tried other fields and the same result.
Any suggestions or help with this problem.
regards
Ricardo
There are basically two different routes you usually take when creating an AJAX action: letting the server render the HTML, or just sending data back to the browser and let the browser render the HTML. The code you have posted is a mixture of the two - that's why it's not working. The jQuery AJAX call is expecting JSON data back from the server, but the server is sending the HTML rendered by the Views\Home\Nuevo.cshtml view. Let's look at what these two different approaches might look like.
Server-Rendered Approach
You need to add an HTML element that will display the result. We will call it NuevoResult. And we also need some code that will put the response there. The easiest way is jQuery's .html() method.
<div id="NuevoResult"></div>
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
// ... also 'contentType' and 'data' if you're actually sending anything to the server...
dataType: 'html',
success: function (data) {
$('#NuevoResult').html(data);
}
});
}
</script>
We also need a Views\Home\Nuevo.cshtml view for the server to render. It might look like:
#model MyCoolNamespace.Persona
<h3>New person created!</h3>
<p>Created on #string.Format("{0:d}", Model.Fecha) at #string.Format("{0:t}", Model.Hora).</p>
This is all the HTML we want to return from this action. We don't want it to be wrapped in any layout. To do this, we need to make sure we return PartialView(persona) instead of return View(persona).
Browser-Rendered Approach
For the browser rendered approach, we'll go ahead and have the HTML ready on the browser, but hidden. We'll fill it in with the correct information and display it when we receive a response from the server.
<div id="NuevoResult" style="display:none">
<h3>New person created!</h3>
<p>Created on <span id="Fecha"></span> at <span id="Hora"></span>.</p>
</div>
<script type= "text/javascript">
function ParseJSONDateTime(value) {
// from http://stackoverflow.com/questions/206384/how-to-format-a-json-date/2316066#2316066
return new Date(parseInt(value.substr(6)));
}
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
// ... also 'contentType' and 'data' if you're actually sending anything to the server...
dataType: 'json',
success: function (data) {
$('#Fecha').text(ParseJSONDateTime(data.Fecha).toLocaleDateString());
$('#Hora').text(ParseJSONDateTime(data.Hora).toLocaleTimeString());
$('#NuevoResult').show();
}
});
}
</script>
And then in the MVC action, use return Json(persona) to send the data back to the browser.
A few more notes...
The .NET DateTime structure holds both date and time information, so there's no need to have separate Fecha and Hora properties. Consider replacing with a single CreatedTimestamp property.
If you're still having trouble, Firefox's Firebug extension, Internet Explorer's Developer Tools, and Chrome's Developer Tools can be very helpful in figuring out what is wrong, allowing you to see exactly what was returned from the server.
Hi if i'm correct the problem is that the textbox values remain empty after you fired the function. The reason behind this is that your javascript function returns the data in the
success : function() {} part.
So what you have to do is return some kind of Json and then place the correct values in the textbox.
Javascript:
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
success: function(data) {
//Do stuff with your data
}
});
c#:
[HttpPost]
public ActionResult Nuevo()
{
Persona persona = new Persona();
persona.Fecha = DateTime.Now;
persona.Hora = DateTime.Now;
return Json(persona, JsonRequestBehavior.AllowGet);
}
This is my view, I use typed views:
#model MvcJavaScript.Models.Persona
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({}),
success: function (data) {
}
});
}
</script>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { sololectura = true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { sololectura = true })</td>
</tr>
</tbody>
</table>
}
If you are returning just a json object from the post call, you can write the success function in you ajax post back like below.
success : function(data) {
$('#inputFecha').html(data.Fecha);
$('#inputHora').html(data.Hora);
}
However if you are returning the view itself (which it looks like from your code), write the success function like this
success : function(data) {
$('#formContainer').html(data); // where formContainer is the control containing your form - may be an html body.
}
EDIT
since you have posted the view, change the Html.TextBoxFor lines for Fecha and Hora like below and use the success function given further below,
#Html.TextBoxFor(u => u.Fecha, new { sololectura = true, id="inputFecha" })
#Html.TextBoxFor(u => u.Hora, new { sololectura = true, id="inputHora" })
success : function(data) {
$('#inputFecha').html(data.Fecha);
$('#inputHora').html(data.Hora);
}
You can try this:
C#
[HttpPost] // Why do you need to use POST method?
public JsonResult Nuevo()
{
return Json(new { Fecha = DateTime.Now, Hora = DateTime.Now });
// if use get: return Json(object, JsonRequestBehavior.AllowGet);
}
HTML:
<button id="button-nuevo">Nuevo</button>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<input type="hidden" id="url-nuevo" value="#Url.Action("Nuevo", "Home")" />
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { #readonly=true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { #readonly = true })</td>
</tr>
</tbody>
</table>
}
JS
function dateFormat(d) {
var date = d.getDate(),
month = d.getMonth() + 1,
year = d.getFullYear();
retur (month > 9 : month ? '0' + month) + "/" + (date > 9 : date ? '0' + date) + "/" + year;
}
$('#button-nuevo').bind('click', function(event) {
var $formContext = $('#formPersona');
$.post($('#url-nuevo').val(), {}, function(data){
//UPDATE
var fecha = new Date(parseInt(data.Fecha.substr(6, 13)));
var hora = new Date(parseInt(data.Hora.substr(6, 13)));
$formContext.find('#Fecha').val(dateFormat(fecha));
$formContext.find('#Hora').val(dateFormat(hora));
}, "json");
});
Update based on this answer
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;
});
});