How can I refresh my partial view on my parent index after a modal update to add new information? - ajax

I am certain this question has been asked before, I don't think there is anything unique about my situation but let me explain. I have my Index View (Parent), on that Index View there is a partial View Dataset Contacts "links" (child), I have an Add Contact button, which pops a Modal and allows me to submit the form data to add to the database, when I return I want to only refresh the partial view of links. Note: the Controller Action Dataset_Contacts below needs to fire in order to refresh the partial view (child). It might go without saying, but I don't see this happening with my current code. Any assistance will be appreciated.
on my Index View index.cshtml I have the following code to render my partial View
<div class="section_container2">
#{ Html.RenderAction("Dataset_Contacts", "Home"); }
</div>
Here is the controller:
[ChildActionOnly]
public ActionResult Dataset_Contacts()
{
// Retrieve contacts in the Dataset (Contact)
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
var returned = new Dataset_Contact_View();
var dataset = new Dataset();
var contacts = new List<Contact>();
var contact_types = new List<Contact_Type>();
using (var client = new HttpClient())
{
dataset = JsonConvert.DeserializeObject<Dataset>(datasetResponse);
contact_types = JsonConvert.DeserializeObject<List<Contact_Type>>(ContactTypeResponse);
// Set up the UI
var ds_contact = new List<ContactView>();
foreach (Contact c in dataset.Contact)
{
foreach (Contact_Type t in contact_types)
{
if (c.Contact_Type_ID == t.Contact_Type_ID)
{
var cv = new ContactView();
cv.contact_id = c.Contact_ID;
cv.contact_type = t.Description;
returned.Dataset_Contacts.Add(cv);
}
}
}
}
return PartialView(returned);
}
Here is my Partial View Dataset_Contacts.cshtml
#model ResearchDataInventoryWeb.Models.Dataset_Contact_View
<table>
#{
var count = 1;
foreach (var ct in Model.Dataset_Contacts)
{
if (count == 1)
{
#Html.Raw("<tr>")
#Html.Raw("<td>")
<span class="link" style="margin-left:10px;">#ct.contact_type</span>
#Html.Raw("</td>")
count++;
}
else if (count == 2)
{
#Html.Raw("<td>")
<span class="link" style="margin-left:300px;">#ct.contact_type</span>
#Html.Raw("</td>")
#Html.Raw("</tr>")
count = 1;
}
}
}
</table>
Also on my Index.cshtml is my Add Contact button, which pops a modal
<div style="float:right;">
<span class="link" style="padding-right:5px;">Add</span>
</div>
jquery for the Modal:
var AddContact = function () {
var url = "../Home/AddContact"
$("#myModalBody").load(url, function () {
$("#myModal").modal("show");
})
};
Controller action for AddContact
public ActionResult AddContact()
{
return PartialView();
}
Modal for AddContact.cshtml
#model ResearchDataInventoryWeb.Models.Contact
<form id="contactForm1">
<div class="section_header2">Contact</div>
<div style="padding-top:5px;">
<table>
<tr>
<td>
<span class="display-label">UCID/Booth ID</span>
</td>
<td>
#Html.TextBoxFor(model => model.Booth_UCID, new { placeholder = "<Booth/UCID>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Type</span>
</td>
<td>
<select class="input-box" id="contact_type">
<option value="contact_type">Contact Type*</option>
<option value="dataset_admin">Dataset Admin</option>
<option value="dataset_Provider">Dataset Provider</option>
<option value="department">Department</option>
<option value="external_collaborator">External Collaborator</option>
<option value="principal_investigator">Principal Investigator</option>
<option value="research_center">Research Center</option>
<option value="vendor">Vendor</option>
</select>
</td>
</tr>
<tr>
<td>
<span class="display-label">Name</span>
</td>
<td>
#Html.TextBoxFor(model => model.First_Name, new { placeholder = "<First Name>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Last_Name, new { placeholder = "<Last Name>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Email</span>
</td>
<td>
#Html.TextBoxFor(model => model.Email, new { placeholder = "<Email 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Email_2, new { placeholder = "<Email 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Phone</span>
</td>
<td>
#Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "<Phone 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Phone_Number_2, new { placeholder = "<Phone 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Job Title</span>
</td>
<td>
#Html.TextBoxFor(model => model.Title_Role, new { placeholder = "<Job Title>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Organization</span>
</td>
<td>
<input class="input-box" type="text" placeholder="<Organization>" />
</td>
</tr>
</table>
<div style="padding-left:10px; margin-top:10px;">
<textarea rows="3" placeholder="Notes"></textarea>
</div>
</div>
<div class="centerButton" style="margin-top: 30px;">
<div style="margin-left:30px">
<submit id="btnSubmit" class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">SAVE</span></submit>
</div>
<div style="margin-left:30px">
<submit class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">REMOVE</span></submit>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var frm = $('#contactForm1').serialize()
$.ajax({
type: "POST",
url: "/Home/AddContact/",
data: frm,
success: function () {
$("#myModal").modal("hide");
}
})
})
})
</script>
and lastly Action for [HttpPost] AddContact(Contact data)
[HttpPost]
public ActionResult AddContact(Contact data)
{
// Update the Database here
return View();
}

My solution:
1. Change ActionResult to JsonResult
{
// Update the Database code
// END
return Json(new
{
dbUpdateResult = "success"
});
}
2. In Ajax:
//Ajax code
...
success: function (ajaxRespond) {
if(ajaxRespond.dbUpdateResult == "success"){
$("#myModal").modal("hide");
reloadTable()
}
}
Then you can use 1:
function reloadTable(){
$('#CONTAINER_ID').load('#Url.Action("Dataset_Contacts", "Home")');
}
Or 2:
function reloadTable(){
let myurl = '#Url.Action("Dataset_Contacts", "Home")';
$.ajax({
type: "GET",
url: myurl,
success: function (data, textStatus, jqXHR) {
$("#CONTAINER_ID").html(data);
},
error: function (requestObject, error, errorThrown) {
console.log(requestObject, error, errorThrown);
alert("Error: can not update table")
}
});
}
So you reload your partial view after successful dbupdate. Please tell me, if I'm wrong...

Related

MVC with AJAX to Remove Table Row

I want to Remove a table row in my index page and before removing the row i have to modify in data base and show a pop to confirm the delete action. But while i delete the row it deleted in database but my page is not refreshed after executing the Success action in Ajax. There the code below i write for my view and controller and also giving my definition of model as reference.
// Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using LAMS_Master.Models;
namespace LAMS_Master.Controllers
{
public class Acquisition_Lease_Case_RecordController : Controller
{
private ApplicationDbContext db;
public Acquisition_Lease_Case_RecordController()
{
db = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
db.Dispose();
}
// GET: Acquisition_Lease_Case_Record
public ActionResult Index()
{
List<acquisition_lease_case_record_master> listdata = new List<acquisition_lease_case_record_master>();
foreach(var d in db.acquisition_lease_case_record_master.Where(c => c.int_deleted_sts == 0).Include(c => c.vill_code).ToList())
{
d.chrv_land_class_cd = db.landclasslistmaster.Where(c => c.chrv_landclass_cd == d.chrv_land_class_cd).Select(c => c.chrv_landclass).SingleOrDefault();
listdata.Add(d);
}
return View("Index",listdata);
}
public ActionResult Create()
{
ViewBag.village = new SelectList(db.village_master.Where(c => c.int_deleted_sts == 0).ToList(), "chrv_vill_code", "chrv_vill_name");
ViewBag.landclass = new SelectList(db.landclasslistmaster.ToList(), "chrv_landclass_cd", "chrv_landclass");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(acquisition_lease_case_record_master alcrm)
{
if (ModelState.IsValid)
{
alcrm.fk_chrv_proj_code = "LAMS111811PCB06";
alcrm.int_created_by = 0;
alcrm.int_deleted_sts = 0;
alcrm.chrv_ip_address = UilityMaster.GetLocalIPAddress();
db.acquisition_lease_case_record_master.Add(alcrm);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.village = new SelectList(db.village_master.Where(c => c.int_deleted_sts == 0).ToList(), "chrv_vill_code", "chrv_vill_name");
ViewBag.landclass = new SelectList(db.landclasslistmaster.ToList(), "chrv_landclass_cd", "chrv_landclass");
return View();
}
[HttpGet]
public ActionResult Edit(string case_no)
{
var data = db.acquisition_lease_case_record_master.Include(c=>c.vill_code).Where(c=>c.chrv_case_no==case_no).SingleOrDefault();
data.chrv_land_class_cd = db.landclasslistmaster.Where(c => c.chrv_landclass_cd == data.chrv_land_class_cd).Select(c => c.chrv_landclass).SingleOrDefault();
return View("EditALCRM", data);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(acquisition_lease_case_record_master alcrmedit)
{
if (alcrmedit.num_case_area!=null && alcrmedit.tms_case_dt!=null && alcrmedit.chrv_case_no!=null)
{
var casefromdb = db.acquisition_lease_case_record_master.Find(alcrmedit.chrv_case_no);
casefromdb.num_case_area = alcrmedit.num_case_area;
casefromdb.tms_case_dt = alcrmedit.tms_case_dt;
db.Entry(casefromdb).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View("EditALCRM", alcrmedit);
}
public JsonResult DeleteCaseRecord(string case_no)
{
var deletedata = db.acquisition_lease_case_record_master.Find(case_no);
bool result = false;
if (deletedata != null)
{
deletedata.int_deleted_sts = 1;
db.Entry(deletedata).State = EntityState.Modified;
db.SaveChanges();
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
//Index page
#model IEnumerable<LAMS_Master.Models.acquisition_lease_case_record_master>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="wrapper">
<div class="panel panel-default">
<h3 class="panel-heading">Case Details</h3>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Village</th>
<th>Land Class</th>
<th>Case No</th>
<th>Case Date</th>
<th>Case Area</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var v in Model)
{
<tr id="#v.chrv_case_no">
<td>
#v.vill_code.chrv_vill_name
</td>
<td>
#v.chrv_land_class_cd
</td>
<td>
#v.chrv_case_no
</td>
<td>
#v.tms_case_dt.ToString("dd-MMM-yyyy")
</td>
<td>
#v.num_case_area
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Acquisition_Lease_Case_Record", new { case_no = v.chrv_case_no }, null) |
Delete
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<input type="hidden" id="hiddencaseno" value="" />
</div>
#*Modal Defination*#
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">Delete</h3>
</div>
<div class="modal-body">
<h4>Are you sure to delete ?</h4>
<div style="text-align:center;display:none" id="loaderDiv">
<img src="~/Images/loader.gif" width="150" />
</div>
</div>
<div class="modal-footer">
Cancel
Confirm
</div>
</div>
</div>
</div>
// Script for index page
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
var ConfirmDelete = function (actid) {
$("#hiddencaseno").val(actid);
$("#myModal").modal('show');}
var DeleteItem = function () {
$("#loaderDiv").show();
var actid = $("#hiddencaseno").val();
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteCaseRecord")',
data: { case_no: actid },
success: function (result) {
$("#loaderDiv").hide();
$("#myModal").modal('hide');
alert('#' + actid);
$('#'+actid).remove(); }})}
</script>

Jquery Validation on Dom not displaying message

I stumbled upon some code that has jQuery validation which is triggered after an ajax call that adds items to the DOM. The validation is working but the message is missing. just the field is highlighted. I have been playing with this for a while to get it to work, but so far no luck. Any ideas, thoughts appreciated.
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var otherIncomesCount = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var count = otherIncomesCount;
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
});
The validation succeeds for both required on additionalIncomeTypeIDMenu, and required and positive on amountTextBox, but the messages for both fail to show up:
function addOtherIncomeValidation(container) {
if (container) {
var additionalIncomeTypeIdMenu = $(container).find('select.other-income-type-id');
var amountTextBox = $(container).find('input.other-income-amount');
$(additionalIncomeTypeIdMenu).rules('add', {
required: true,
messages: {
required: 'Please select an income type'
}
});
$(amountTextBox).rules('add', {
required: true,
positive: true,
messages: { positive: 'must be positive number'
}
});
}
}
BTW The ajax call returns a partial EditorTemplate here, which you can see uses ValidationMessageFor.
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />#Html.ValidationMessageFor(x => x.AdditionalIncomeTypeId)
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />#Html.ValidationMessageFor(x => x.Amount)
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
HTML:
<div id="OtherIncome" class="applicant-section">
<h2 class="header2">Other Income</h2>
<div class="cornerForm">
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_0__Id" name="OtherIncome[0].Id" type="hidden" value="385" />
<label class="other-income-type-id-label" for="OtherIncome_0__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_0__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_0__AdditionalIncomeTypeId" name="OtherIncome[0].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option selected="selected" value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_0__Amount" name="OtherIncome[0].Amount" style="" type="text" value="0.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XNxxxxx753/385">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_1__Id" name="OtherIncome[1].Id" type="hidden" value="412" />
<label class="other-income-type-id-label" for="OtherIncome_1__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_1__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_1__AdditionalIncomeTypeId" name="OtherIncome[1].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option selected="selected" value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_1__Amount" name="OtherIncome[1].Amount" style="" type="text" value="22.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XN42093753/412">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div id="additional-other-income"></div>
<input id="numberOfNewOtherIncomes" name="numberOfNewOtherIncomes" type="hidden" value="0" />
<input data-val="true" data-val-number="The field OriginalOtherIncomeTotal must be a number." id="OriginalOtherIncomeTotal" name="OriginalOtherIncomeTotal" type="hidden" value="22.0000" />
<a class="editable-link" href="/Applicant/AddOtherIncome?appId=XNxxxxx753" id="add-other-income-link">Add Other Income</a>
</div> </div>
Validation code:
$.validator.addMethod('positive', function(value, element) {
var check = true;
if (value < 0) {
check = false;
}
return this.optional(element) || check;
}, "Value must be a positive number."
);
I didn't think I would find my own answer but I did. first I have to apologize for my response to #Sparky with his request for rendered HTML. I did a "View page source" but that didn't include all the stuff which was added from the ajax call after the server delivered it's stuff. I suspect if I did include the extra DOM stuff at first, you would have pinpointed the issue sooner. My bad. Now on to the answer.
It appears that when injecting an EditorTemplate into the DOM in the way shown above, it doesn't properly process the page like you would expect in MVC. The code for #Html.ValidationMessageFor simply does not get parsed AT ALL. I am a little new to validation as you can see so I don't know why it behaves this way. To solve my problem here is what I did:
I updated my Editor Template slightly to look like this:
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />
#Html.ValidationMessageFor(x=>x.AdditionalIncomeTypeId)
<span id="AdditionalIncomeTypeIdValidation"></span>
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />
#Html.ValidationMessageFor(x=>x.Amount)
<span id="amountValidation"></span>
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
Notice the new span tags, which is are added next to the #Html.ValidationMessageFor.
then in my success function from the ajax call in javascript I made these changes:
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var count = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var amountValidation = $(item).find('#amountValidation');
var typeIdValidation = $(item).find('#AdditionalIncomeTypeIdValidation');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
amountValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'Amount')
.attr('data-valmsg-replace','true');
typeIdValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'AdditionalIncomeTypeId')
.attr('data-valmsg-replace','true');
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
notice I am manually adding in the missing validation spans that were not rendering. Now the validation message shows up at validation! Yay. I am not sure however that this is the best fix. It looks and smells like a hack, but I got it to work. I am sure it can be done a better way. Thanks again for interaction and feedback.

Video file upload using ajax in mvc 3

How can I upload any video format in my project. Is it the same as uploading image?,coz I can upload image but I can't upload any video. Any tips? Thank you.
I update my question,as I said I can upload image using the code below,my problem is how can I upload video at the same time and with some other data.
#model BookingCMS.Models.Booking
#{
ViewBag.Title = "Index";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="#Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.fileupload.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/jquery.fileupload-ui.css")" rel="stylesheet" type="text/css" />
<br />
<br />
<fieldset>
<legend>
<h2>
Add Movie</h2>
</legend>
<br />
<table id="table-2">
<tbody>
<tr>
<td>
Movie Name
</td>
<td>#Html.TextBoxFor(model => model.MovieName, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Status
</td>
<td>#Html.CheckBoxFor(model => model.Status)
</td>
</tr>
<tr>
<td>
Showing Type
</td>
<td>#Html.DropDownList("ShowingTypes", ViewBag.ShowingType as IEnumerable<SelectListItem>, "Select Type")
</td>
</tr>
<tr>
<td>
Movie Codes
</td>
<td>
<input class="checkbox" type="checkbox" id="SC" />
<label class="label">
Standard Cinema</label>
#Html.TextBoxFor(model => model.StandardCinema, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="I2D" />
<label class="label">
IMAX2D</label>
#Html.TextBoxFor(model => model.Imax2D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="I3D" />
<label class="label">
IMAX 3D</label>
#Html.TextBoxFor(model => model.Imax3D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DC" />
<label class="label">
Directors Club</label>
#Html.TextBoxFor(model => model.DirectorsClub, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DT2D" />
<label class="label">
Digital Theatre 2D</label>
#Html.TextBoxFor(model => model.DigitalTheatre2D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DT3D" />
<label class="label">
Digital Theatre 3D</label>
#Html.TextBoxFor(model => model.DigitalTheatre3D, new { #class = "textbox" })
</td>
</tr>
<tr>
<td>
Cast
</td>
<td>#Html.TextBoxFor(model => model.Cast, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Rating
</td>
<td>#Html.TextBoxFor(model => model.Rating, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Genre
</td>
<td>#Html.TextBoxFor(model => model.Genre, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Cinexclusive
</td>
<td>#Html.CheckBoxFor(model => model.Cinexclusive)
</td>
</tr>
<tr>
<td>
Blurb
</td>
<td>#Html.TextAreaFor(model => model.Blurb, new { style = "width:500px; height: 150px" })
</td>
</tr>
<tr>
<td>
Synopsis
</td>
<td>#Html.TextAreaFor(model => model.Synopsis, new { style = "width:500px; height: 150px" })
</td>
</tr>
<tr>
<td>
Poster Homepage
</td>
<td style>
<form id="file_upload" action="/Movies/UploadFiles" method="POST" enctype="multipart/form-data">
<div class="fileupload-buttonbar">
#*<div class="progressbar fileupload-progressbar">
</div>*#
<div id="file_name">
</div>
<div id="file_type">
</div>
<div id="file_size">
</div>
<div id="show_image"></div>
<span class="fileinput-button"><a href="javascript:void(0)" class="upload-image">
Upload image</a>
<input type="file" name="files[]" multiple id="file" />
</span>
</div>
</form>
#*#Html.TextBox("PosterHomepage", (string)ViewBag.PosterHomepage, new { #class = "editor-field" })*#
</td>
</tr>
<tr>
<td>
Running Time
</td>
<td>#Html.TextBoxFor(model => model.RunningTime, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Trailer
</td>
<td>#Html.TextBoxFor(model => model.Trailer, new { #class = "editor-field" }) #*Here is my problem ..how can I upload video with some other data*#
</td>
</tr>
</tbody>
</table>
<br />
<div style="float: left">
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnCancel" value="Cancel" />
</div>
</fieldset>
<script type="text/javascript">
$(document).ready(function () {
$('.progressbar').progressbar({ value: 0 });
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
progressall: function (e, data) {
$(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
},
done: function (e, data) {
$('#file_name').html(data.result.name);
$('#file_type').html(data.result.type);
$('#file_size').html(data.result.size);
$('#show_image').html('<img src="/home/image/' + data.result.name + '" />');
$('#file_name').css({ display: 'none' });
$('#file_type').css({ display: 'none' });
$('#file_size').css({ display: 'none' });
//visibility: hidden;
$(this).find('.progressbar').progressbar({ value: 100 });
}
});
});
$('#StandardCinema').hide();
$('#Imax2D').hide();
$('#Imax3D').hide();
$('#DirectorsClub').hide();
$('#DigitalTheatre2D').hide();
$('#DigitalTheatre3D').hide();
$('#SC').click(function () {
var check = $("#SC").is(':checked');//.attr('checked');
if (check == true) {
$('#StandardCinema').show();
$('#StandardCinema').focus();
}
else {
$('#StandardCinema').hide();
}
});
$('#I2D').click(function () {
var check = $("#I2D").is(':checked');
if (check == true) {
$('#Imax2D').show();
$('#Imax2D').focus();
}
else {
$('#Imax2D').hide();
}
});
$('#I3D').click(function () {
var check = $("#I3D").is(':checked');
if (check == true) {
$('#Imax3D').show();
$('#Imax3D').focus();
}
else {
$('#Imax3D').hide();
}
});
$('#DC').click(function () {
var check = $("#DC").is(':checked');
if (check == true) {
$('#DirectorsClub').show();
$('#DirectorsClub').focus();
}
else {
$('#DirectorsClub').hide();
}
});
$('#DT2D').click(function () {
var check = $("#DT2D").is(':checked');
if (check == true) {
$('#DigitalTheatre2D').show();
$('#DigitalTheatre2D').focus();
}
else {
$('#DigitalTheatre2D').hide();
}
});
$('#DT3D').click(function () {
var check = $("#DT3D").is(':checked');
if (check == true) {
$('#DigitalTheatre3D').show();
$('#DigitalTheatre3D').focus();
}
else {
$('#DigitalTheatre3D').hide();
}
});
$('#btnAdd').click(function () {
var e = document.getElementById("file_name");
var content = e.innerHTML;
//alert(content);
var _MovieName = $('#MovieName').val();
var _Active = $('#Status').val();
var _ShowingTypes = $('#ShowingTypes :selected').val();
var _ShowingTypesText = $('#ShowingTypes :selected').text();
var _Cast = $('#Cast').val();
var _Rating = $('#Rating').val();
var _Blurb = $('#Blurb').val();
var _Synopsis = $('#Synopsis').val();
var _RunningTime = $('#RunningTime').val();
var _Genre = $('#Genre').val();
var _Cinexclusive = $('#Cinexclusive');
var _Trailer = $('#Trailer').val();
var _PosterHomepage = content;
var _SC = $('#StandardCinema').val();
var _I2D = $('#Imax2D').val();
var _I3D = $('#Imax3D').val();
var _DC = $('#DirectorsClub').val();
var _DT2D = $('#DigitalTheatre2D').val();
var _DT3D = $('#DigitalTheatre3D').val();
var isSC = $("#SC").attr('checked') ? true : false;
var isI2D = $("#I2D").attr('checked') ? true : false;
var isI3D = $("#I3D").attr('checked') ? true : false;
var isDC = $("#DC").attr('checked') ? true : false;
var isDT2D = $("#DT2D").attr('checked') ? true : false;
var isDT3D = $("#DT3D").attr('checked') ? true : false;
var isActive = $('#Status').attr('checked') ? true : false;
var isCinex = $('#Cinexclusive').attr('checked') ? true : false;
if (_ShowingTypesText == "Select Type") {
alert("Showing Type is required.");
return false;
}
if (isSC == true & _SC == "") {
alert("Standard Cinema was selected! Movie code is required.");
$('#StandardCinema').focus();
return false;
}
if (isI2D == true & _I2D == "") {
alert("IMAX 2D was selected! Movie code is required.");
$('#Imax2D').focus();
return false;
}
if (isI3D == true & _I3D == "") {
alert("IMAX 3D was selected! Movie code is required.");
$('#Imax3D').focus();
return false;
}
if (isDC == true & _DC == "") {
alert("Director's Club was selected! Movie code is required.");
$('#DirectorsClub').focus();
return false;
}
if (isDT2D == true & _DT2D == "") {
alert("Digital Theatre 2D was selected! Movie code is required.");
$('#DigitalTheatre2D').focus();
return false;
}
if (isDT3D == true & _DT3D == "") {
alert("Digital Theatre 3D was selected! Movie code is required.");
$('#DigitalTheatre3D').focus();
return false;
}
var postData = {
moviename: _MovieName,
status: isActive,
showingtype: _ShowingTypes,
cast: _Cast,
rating: _Rating,
genre: _Genre,
cinexclusive: isCinex,
blurb: _Blurb,
synopsis: _Synopsis,
runningtime: _RunningTime,
trailer: _Trailer,
posterhompage: _PosterHomepage,
sc: _SC,
i2d: _I2D,
i3d: _I3D,
dc: _DC,
dt2d: _DT2D,
dt3d: _DT3D
};
$.ajax({
type: "POST",
url: "/Movies/CreateMovie",
dataType: "json",
traditional: true,
data: postData,
cache: false,
success: function (data) {
if (data.Result == "Success") {
jAlert(data.Message, "Notification", function () {
window.location = '/Home/Index';
});
}
else
jAlert(data.Message, "Notification"); //, function () {
//$('#code').focus();
//});
}
});
});
$("#btnCancel").click(function () {
window.location = "/Home/Index/";
});
</script>
Controller:
public FilePathResult Image()
{
string filename = Request.Url.AbsolutePath.Replace("/home/image", "");
string contentType = "";
var filePath = new FileInfo(Server.MapPath("~/Images") + filename);
var index = filename.LastIndexOf(".") + 1;
var extension = filename.Substring(index).ToUpperInvariant();
// Fix for IE not handling jpg image types
contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);
return File(filePath.FullName, contentType);
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadHomePage>();
foreach (string file in Request.Files)
{
HttpPostedFileBase image = Request.Files[file] as HttpPostedFileBase;
if (image.ContentLength == 0)
continue;
string savedFileName = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(image.FileName));
image.SaveAs(savedFileName);
r.Add(new UploadHomePage()
{
Name = image.FileName,
Length = image.ContentLength,
Type = image.ContentType
});
}
ViewBag.PosterHomepage = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(r[0].Name));
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
[HttpPost]
public ActionResult CreateMovie(string moviename, bool status, int showingtype, string cast, string rating, string genre, bool cinexclusive, string blurb, string synopsis, string runningtime, string trailer, string posterhompage, string sc, string i2d, string i3d, string dc, string dt2d, string dt3d)
{
try
{
//Saving process
if (_WebResult.Result == 0)
{
return Json(new { Result = "Success", Message = _WebResult.Message.ToString() });
}
else
{
return Json(new { Result = "Error", Message = _WebResult.Message.ToString() });
}
}
catch (Exception)
{
return Json(new { Result = "Error", Message = "" + " failed to save." });
}
}

How to display text from a dropdown in MVC

I have a partial view that has to display records on the change of dropdown. The values are coming correctly but it is not being displayed in the tex boxes. Please help. THe code of my partial view looks like below
#using (Ajax.BeginForm("W2State", new AjaxOptions() { UpdateTargetId = "model", OnSuccess = "w2Updated", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" } ))
{
<fieldset id="currencyView" class="detailView">
<table>
<tr>
<td style="width: 100px;">Select Agency </td>
<td>
#*#Html.DropDownListFor(model => model.ReportingAgencies, new SelectList(Model.ReportingAgencies, "SelectedAgency.AgencyGuid", "SelectedAgency.Name"), new { id = "dropDownReportAgencies" })*#
#Html.DropDownListFor(model => model.ReportingAgencies, new SelectList(Model.ReportingAgencies, "SelectedAgency.AgencyGuid", "SelectedAgency.Name"), "--Select An Agency--", new { id = "dropDownReportAgencies" })
</td>
</tr>
<tr class="seperator"></tr>
<tr class="seperator"></tr>
<tr>
<td style="width: 100px;">#Html.LabelFor(model => model.W2StateLocal.Wages)</td>
<td> #Html.TextBoxFor(model => model.W2StateLocal.Wages)</td>
</tr>
<tr>
<td style="width: 100px;">#Html.LabelFor(model => model.W2StateLocal.Tax)</td>
<td>#Html.TextBoxFor(model => model.W2StateLocal.Tax)</td>
</tr>
</table>
<div id="rightButtonControls">
#if (Model.IsEditable)
{
<button id="btnSave" value="save">Save</button>
}
</div>
</fieldset>
}
#Html.HiddenFor(model => model.CompanyId, new { id = "CompanyId" })
#Html.HiddenFor(model => model.EmployeeId, new { id = "EmployeeId" })
#Html.HiddenFor(model => model.FilingYear, new { id = "FilingYear" })
<script type="text/javascript">
$(document).ready(function () {
$("#divLoader").css('display', 'none');
$('#dropDownReportAgencies').change(function () {
var selectedAgency = $('#dropDownReportAgencies option:selected').val();
var CompanyId = $('#CompanyId').val();
var EmployeeId = $('#EmployeeId').val();
var FilingYear = $('#FilingYear').val();
var url = '#Url.Action("W2State", "W2Generation")';
$.get(url, { agencyId: selectedAgency, companyId: CompanyId, employeeId: EmployeeId, filingYear: FilingYear },
function (data) {
});
});
});
You want to get text from dropdown in mvc through jQuery...
Your code is right but just missing something.. You used
var selectedAgency = $('#dropDownReportAgencies option:selected').val();
but instead of 'val' you have to use 'text'.. it means
var selectedAgency = $("#dropDownReportAgencies option:selected").text();
Try this....

MVC 3 Razor - Form not posting back to controller

I am using MVC 3 and Razor, attempting to post a form back to a controller from a telerik window (telerik.window.create) that loads a partial view. Im not sure how to post this so ill just post the code in order of execution and explain it as I go.
First an anchor is clicked, and onClick calls:
function showScheduleWindow(action, configId) {
var onCloseAjaxWindow = function () { var grid = $("#SubscriptionGrid").data("tGrid"); if (grid) { grid.rebind(); } };
CreateAjaxWindow("Create Schedule", true, false, 420, 305, "/FiscalSchedule/" + action + "/" + configId, onCloseAjaxWindow);
}
And the CrateAjaxWindow method:
function CreateAjaxWindow(title, modal, rezible, width, height, url, fOnClose) {
var lookupWindow = $.telerik.window.create({
title: title,
modal: modal,
rezible: rezible,
width: width,
height: height,
onClose: function (e) {
e.preventDefault();
lookupWindow.data('tWindow').destroy();
fOnClose();
}
});
lookupWindow.data('tWindow').ajaxRequest(url);
lookupWindow.data('tWindow').center().open();
}
Here is the partial view that is being loaded:
#model WTC.StatementAutomation.Web.Models.FiscalScheduleViewModel
#using WTC.StatementAutomation.Model
#using WTC.StatementAutomation.Web.Extensions
#using (Html.BeginForm("Create", "FiscalSchedule", FormMethod.Post, new { id = "FiscalScheduleConfigForm" }))
{
<div id="FiscalScheduleConfigForm" class="stylized">
<div class="top">
<div class="padding">
Using fiscal year end: #Model.FiscalYearEnd.ToString("MM/dd")
</div>
<div class="padding Period">
<table border="0">
<tr>
<th style="width: 120px;"></th>
<th>Effective Date</th>
<th>Next Run</th>
<th>Start From Previous</th>
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasMonthly)
<label>Monthly</label>
</td>
<td>
#{ var month = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.Monthly);}
#month.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#month.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(month.HasRun ? Html.CheckBoxFor(m => month.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => month.BaseSchedule.StartFromPreviousCycle))
</td>
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasQuarterly) Quarterly
</td>
<td>
#{ var quarter = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.Quarterly);}
#quarter.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#quarter.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(quarter.HasRun ? Html.CheckBoxFor(m => quarter.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => quarter.BaseSchedule.StartFromPreviousCycle))
</td >
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasAnnual) Annual
</td>
<td>
#{ var annual = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.Annual);}
#annual.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#annual.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(annual.HasRun ? Html.CheckBoxFor(m => annual.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => annual.BaseSchedule.StartFromPreviousCycle))
</td>
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.HasSemiAnnual) Semi-annual
</td>
<td>
#{ var semi = Model.GetForFiscalPeriod(FiscalPeriodStatementSchedule.FiscalPeriod.SemiAnnual);}
#semi.BaseSchedule.StartDate.ToString("MM/01/yyyy")
</td>
<td>
#semi.BaseSchedule.NextScheduleRun.ToString("MM/dd/yyyy")
</td>
<td class="previous">
#(semi.HasRun ? Html.CheckBoxFor(m => semi.BaseSchedule.StartFromPreviousCycle, new { #disabled = "disabled", #readonly = "readonly" }) : Html.CheckBoxFor(m => semi.BaseSchedule.StartFromPreviousCycle))
</td>
</tr>
</table>
</div>
<div class="padding StartDay">
<span>Run on day:</span>
#Html.TextBoxFor(model => model.StartDay)
<span>of every period.</span>
</div>
</div>
<div class="bottom">
<div class="padding">
<div style="float: left;">
#if (Model.ShowSuccessSave)
{
<div id="successSave" class="label">Changes saved succesfully</div>
}
#Html.ValidationSummary(true)
#Html.HiddenFor(x => x.SubscriptionId)
#Html.HiddenFor(x => x.DeliveryConfigurationId)
#Html.HiddenFor(x => x.FiscalYearEnd)
</div>
<a id="saveSchedule" class="btn" href="">Save</a>
</div>
</div>
</div>
}
<script type="text/javascript">
$(function () {
$('a#saveSchedule').click(function () {
$(this).closest("form").submit();
return false;
});
});
</script>
And finally the controller method:
[HttpPost]
public ActionResult Create(FormCollection formValues, int subscriptionId, int deliveryConfigurationId, int startDay, DateTime fiscalYearEnd)
{
if (ModelState.IsValid)
{
var selectedSchedules = GetCheckedSchedulesFromForm(formValues);
var startFromPrevious = GetFromPreviouSelections(formValues);
this.AddModelErrors(_fiscalScheduleService.AddUpdateSchedules(selectedSchedules, subscriptionId, deliveryConfigurationId, startDay, startFromPrevious));
}
return new RenderJsonResult { Result = new { success = true, action = ModelState.IsValid ? "success" : "showErrors",
message = this.RenderPartialViewToString("_FiscalScheduleConfigForm",
BuildResultViewModel(deliveryConfigurationId, subscriptionId, fiscalYearEnd, ModelState.IsValid)) } };
}
As you can see I am using jQuery to post back to the controller, which I have done on several occasions in the applicaiton, this seems to work fine normally. But with this form, for some reason it is not posting back or stepping into the Create method at all. I am speculating that it has something to do with the parameters on the controller method. But I am fairly new to MVC (coming from ASP.NET world) so Im not really sure what I am doing wrong here. Any help would be greately appreciated!
I was able to get it to post to the controller by modifying the textboxfor for the startDay:
Changed from:
#Html.TextBoxFor(model => model.StartDay)
To:
#Html.TextBoxFor(model => model.StartDay, new { id = "startDay" })
My guess is that you're running on a virtual directory in IIS? That url you're generating is likely the culprit.
Hit F12, check out the network tab (and enable tracing) and see what it's trying to request.
Instead of building the link through text, why not use #Url.Action()? You could store this in an attribute on the a tag (like in an attribute called data-url, for example) and then use that info to make your call. It's pretty easy to pull out the attribute with jQuery, something like this:
$('.your-link-class').click(function(){
var url = $(this).attr('data-url');
// proceed with awesomesauce
});
Would something like that work for you?
[shameless self plug] As far as the controller action signature goes, you might want to look into model binding if you can. One simple class and many of your headaches will go away. You can read more here, read the parts on model binding. There are downloadable samples for different approaches.
Cheers.

Resources