Sent form (list object) to controller AJAX MVC - ajax

I want sent form (list of object) with ajax. But the function serialize() in JS doesnt read in controller
JS File:
function save() {
$.ajax({
url: "/Ocena/AddOcene",
method: "POST",
dataType: "html",
data: {
id: $("#KlasaDDL option:selected").val(),
dodaj: $('#formOceny').serializeArray()
},
success: function (html) {
$('#load').html(html);
}
})
}
$(function () {
var llBtn = $('#saveForm');
llBtn.click(function () {
save();
});
});
In controller I have parametrs:
public ActionResult AddOcene(string id, List<Dodaj_ocene> dodaj)
View:
#model List<biblioteka.Dodaj_ocene>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "formOceny" }))
{
#Html.DropDownListFor(x => Model[0].Przedmiot, (SelectList)ViewBag.Przedmiot, "--Dostępne przedmioty--", new { #class = "form-control" })
#*#Html.DropDownList(m => Model[0].Przedmiot, *#
<p>Wprowadź rodzaj</p>
#Html.TextBoxFor(m => Model[0].Rodzaj, new { #class = "form-control" })
<p>Wprowadź Opis</p>
#Html.TextBoxFor(m => Model[0].Opis, new { #class = "form-control" })
<p>Wybierz wagę ocen:</p>
#Html.DropDownListFor(m => Model[0].Waga, new SelectListItem[] {
new SelectListItem{ Value = "5", Text = "V", Selected = Model[0].Waga == 5 } ,
new SelectListItem{ Value = "4", Text = "IV", Selected = Model[0].Waga == 4 } ,
new SelectListItem{ Value = "3", Text = "III" , Selected =
}, new { #class = "form-control" })
<br /> <br />
<table class="table">
<tr>
</tr>
#for (var index = 0; index < Model.Count; index++)
{
<tr>
<td>#Model[index].ImieNazwisko </td>
<td>
#Html.DropDownListFor(m => Model[index].Wartosc, new SelectListItem[]{
new SelectListItem{ Value = "0", Text = "Brak oceny", Selected = Model[index].Wartosc == 0 } ,
new SelectListItem{ Value = "1", Text = "1" , Selected = Model[index].Wartosc == 1 }
} , new { #class = "form-control" })
</td>
</tr>
}
</table>
<div class="form-group">
<div></div>
<button type="button" class="btn btn-info" id="saveForm">Zapisz</button>
</div>
}
I would be very grateful for a Apparently

Related

Edits in List not being saved when partial view loaded MVC

I'm new to MVC. I have a view which displays the products attached to a Quote (the QuoteDetails). I also have an Ajax.ActionLink)_ for "Add product" which loads a partial view for another product to be entered. The problem is that when the partial view is loaded, edits to the other products not in the partial view are not saved. If no partial view is loaded, edits to the listed products are saved just fine.
Here is the relevant code for the main view:
#model CMSUsersAndRoles.Models.QuoteViewModel
....
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="~/Scripts/jquery.mask.min.js"></script>
#using (Html.BeginForm())
{
....
#Html.HiddenFor(model => model.CustomerId)
#Html.LabelFor(model => model.QuoteId)
#Html.EditorFor(model => model.QuoteId, new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.QuoteId)
.... // more controls for properties of Quote
#Html.LabelFor(model => model.QuoteDetail)
<div id="QuoteDetails">
#for (int i = 0; i < Model.QuoteDetail.Count; i++)
{
#Html.HiddenFor(model => model.QuoteDetail[i].QuoteId, new { htmlAttributes = new { #class = "form-control" } })
....
#Html.EditorFor(model => model.QuoteDetail[i].SKU, new { htmlAttributes = new { #readonly = "readonly", #id = "SKU", #class = "form-control", style = "width: 100px" } })
#Html.EditorFor(model => model.QuoteDetail[i].Amount, new { htmlAttributes = new { #class = "form-control amount", style = "width: 95px" } })
#Html.ValidationMessageFor(model => model.QuoteDetail[i].Amount)
.... // more for controls for properties of QuoteDetail
#Ajax.ActionLink(" ", "DeleteProduct", "QuoteViewModel", new { quoteId = Model.QuoteDetail[i].QuoteId, quoteDetailId = (Model.QuoteDetail[i].QuoteDetailId) },
new AjaxOptions
{
HttpMethod = "POST",
Confirm = "Are you Sure You Want to Delete " + Model.QuoteDetail[i].ProductName,
}, new { #class = "btn btn-danger glyphicon glyphicon-trash" })
</div>
}
#Html.EditorFor(model => model.Subtotal, new { htmlAttributes = new { #class = "form-control subTotal", style = "width: 100px; float:right; clear:left; text-align:right" } })
#Ajax.ActionLink("Add product", "AddProduct", "QuoteViewModel", new { quoteId = Model.QuoteId, quoteDetailId = (Model.QuoteDetail.Count + 1) },
new AjaxOptions
{
UpdateTargetId = "QuoteDetails",
InsertionMode = InsertionMode.InsertAfter
})
}
Here is the partial view:
#model CMSUsersAndRoles.Models.QuoteDetail
#{
ViewBag.Title = "EditQuoteDetail";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="row" class="row">
<table>
#using (Html.BeginCollectionItem("quoteDetail"))
{
<tr>
#Html.HiddenFor(model => model.QuoteId, new { htmlAttributes = new { #class = "form-control" } })
#Html.EditorFor(model => model.SKU, new { htmlAttributes = new { #readonly = "readonly", #id = "SKU", #class = "form-control", style = "width: 100px" } })
#Html.DropDownListFor(model => model.ProductId, new SelectList(ViewBag.ProductData, "ProductId", "Name"), "---Select one---", new { style = "width: 300px !important", htmlAttributes = new { #id = "ProductName", #class = "ProductList" } });
.... // more controls for properties of QuoteDetail
#Ajax.ActionLink(" ", "DeleteProduct", "QuoteViewModel", new { quoteId = Model.QuoteId, quoteDetailId = (Model.QuoteDetailId) },
new AjaxOptions
{
HttpMethod = "POST",
Confirm = "Are you Sure You Want to Delete " + Model.ProductName,
}, new { #class = "btn btn-danger glyphicon glyphicon-trash" })
</tr>
}
</table>
</div>
And here is the controller action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(QuoteViewModel qvm,
[Bind(Include = "CustomerId,SalesRep,FirstName,LastName,Company,Address1,Address2,City,State,PostalCode,WorkPhone,CellPhone,Email,Discount,PaymentTerms")] Customer customer,
[Bind(Include = "QuoteId,QuoteDetailId,ProductId,ProductName,Amount,ListPrice,Discount,Price")] List<QuoteDetail> quoteDetails,
[Bind(Include = "QuoteId,CustomerId,Subtotal,Tax,Total,QuoteDate,GoodUntil,QuoteSent,DateApproved,DateOrdered")] Quote quote)
{
....
}
Can anyone help with this? Any help will be much appreciated.
Your using 2 different techniques here to generate your collection which is causing the issue.
In the main view you have a for loop to generate controls for existing items which is generating the zero-based consecutive indexers, which is what the DefaultModelBinder uses by default. Your html will include name attributes that are for example
<input name="QuoteDetail[0].QuoteId"..../>
<input name="QuoteDetail[1].QuoteId"..../>
<input name="QuoteDetail[2].QuoteId"..../>
But then you add new items using the BeginCollectionItem helper method which generates the collection indexer as a Guid so that new inputs will be (where xxx is a Guid)
<input name="QuoteDetail[xxxx].QuoteId"..../>
and also includes a
<input name="QuoteDetail.Index" value="xxxx" ... />
which is used by the DefaultModelBinder to match non zero-based non consecutive indexers. You cannot use both techniques.
To solve this, you can either add an input for the indexer in the for loop
#for (int i = 0; i < Model.QuoteDetail.Count; i++)
{
....
<input type="hidden" name="QuoteDetail.Index" value="#i" />
}
or change the loop to use the partial view containing the BeginCollectionItem method in each iteration
#foreach(var item in Model.QuoteDetail)
{
#Html.Partial("xxxx", item) // replace xxxx with the name of your partial
}

Button isn't sending to correct view

I am using ajax to send values to my controller from the view:
View where information is collected to send to a different controller:
#using (Html.BeginForm(null, null, FormMethod.Get, htmlAttributes: new { id = "GenerateForm" }))
{
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose AC:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("AC", null, "-- Select AC --", htmlAttributes: new { id = "AC", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Choose Month:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Months", null, "-- Select Month --", htmlAttributes: new { id = "Month", #class = "form-control" })
</div>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Year:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Years", null, "-- Select Year --", htmlAttributes: new { id = "Year", #class = "form-control" })
</div>
</div>
</div>
<br />
<input type="submit" id="SendToController" class="btn btn-primary" value="Generate" />
}
<script type="text/javascript">
$('#SendToController').on('click', function() {
sendToController();
return false;
});
function sendToController(){
var selectedAC = $('#AC').val();
var selectedMonth = $('#Month').val();
var chosenYear = $('#Year').val();
$.ajax({
url: '/MonthReports/Generate',
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){},
});
}
Controller Method:
public ActionResult Generate(int id, int monthValue, string year)
{
List<DailySum> lstDailySum = db.DailySum.Where(x => x.AID == id && x.Day.Month == monthValue + 1 && x.Day.Year.ToString() == year && x.deleted == false).ToList();
List<string> lstInc = lstDailySum.Select(x => x.codeAC.text).Distinct().ToList();
List<MReport> lstMReport = new List<MReport>();
foreach (var inc in lstInc)
{
MReport mReport = new MReport();
mReport.Inc = inc;
mReport.Count = lstDailySum.Where(x => x.codeAC.text == incident).Count();
lstMReport.Add(mReport);
}
return View(lstMReport);
}
Now the values are being passed through when the button is clicked, and the whole method works, except the View doesn't show up.. it just stays on the View where the button was originally clicked... no Generate View appears.
I have placed a breakpoint on the Generate view and it does get hit but the view doesn't show?
I don't know how else to explain it.. the cshtml code is hit with a breakpoint, but the page doesn't show.. it just stays on the page where the button was clicked.
Any help is appreciated.
Because you are using ajax, you should handle the data in the success callback of your ajax call. The way your code is written, you do nothing with the view. The View is rendered to the data variable.
Try something like this:
$.ajax({
url: '/MonthReports/Generate',
data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
type: 'GET',
cache: false,
success: function(data){
$("body").html(data);
}
});

How can I prevent a partial view from disappearing upon submit?

I’m using BeginForm inside of a child view. When I submit the form I’m still on the parent view but the child view goes away. I would like for the information to be submitted but the form to remain until the user wants to load another partial view or move away from the page entirely. Is there a way to prevent the page from disappearing upon submit? Here’s what my BeginForm looks like:
using (Html.BeginForm("Action", "Controller", new { fromTeacherPage = true, searchTeacher = instructorName, selectedDepartment = Model.Assignments.FirstOrDefault().departmentNumber, id = Model.Assignments.FirstOrDefault().InstructorId, strCategoryName = #ViewBag.categoryname }, FormMethod.Post, new { #name = "formName", #class = "nameOfClass" }))
{
//code for form here
<button id="submitButton" class="submitButton">Submit</button><br />
}
UPDATE:
<script type="text/javascript">
$(document).ready(function () {
$("#datep").datepicker({ showOn: "both", buttonText: "Select Date", changeMonth: true, changeYear: true, yearRange: "-2:+2", showOtherMonths: true, onSelect: function (date, datepickder) {
var sltdDate = { selectedDate: date };
$.ajax({
type: "GET",
url: "/Schedule/GetSchedule",
data: sltdDate,
datatype: "html",
success: function (data) {
$("#returnedData").html(data);
$("#returnedData #dateContainer").remove();
$("<button>Hide</button>").appendTo("#homeworkUpdateId-0")
}
});
}
});
});
</script>
#{
int? intTeacherID = Convert.ToInt32(HttpContext.Current.Session["intTeacherId"]);
string instructorName = (from x in Model.Enrollments where x.InstructorId == intTeacherID select x.InstructorFullName).FirstOrDefault();
}
<div id="dateContainer">
<label for ="datep">Date: </label><input id="datep" />
</div>
<div id="returnedData">
#if (Model.Assignments != null)
{
using (Html.BeginForm("Action", "Controller", new { fromTeacherPage = true, searchTeacher = instructorName, selectedDepartment = Model.Assignments.FirstOrDefault().departmentNumber, id = Model.Assignments.FirstOrDefault().teacherId, strCategoryName = #ViewBag.categoryname }, FormMethod.Post, new { #name = "formName", #class = "submitAttendance" }))
{
<table>
<tr>
<th>
Grade
</th>
<th>
Attendance
</th>
<th>
Clas Day
</th>
<th>
Assignment Type
</th>
<th>
Overall Grade
</th>
</tr>
#foreach (var assignment in Model.Assignments.Select((x, i) => new { Data = x, Index = i }))
{
int asgnIndex = assignment.Index;
<tr id="rowId+#asgnIndex">
<td>
<div id="homeworkUpdateId-#asgnIndex">
#Html.TextBox("HomeworkGrade", assignment.Data.HomeworkGrade.ToString(), new { style = "width:55px; text-align: center" })
</div>
</td>
</table>
<button id="submitButton" class="submitButton">Submit </button><br />
}
}
</div>
You are using
using(Html.BeginForm()){}
this will refresh the whole page if you only want to reload some section inside your view you have to use
using (Ajax.BeginForm("Action", "Controller", null, new AjaxOptions {UpdateTargetId = "divToUpdate", InsertionMode = InsertionMode.Replace, HttpMethod = "GET"}, new {id = "someIdFOrm"}))

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....

Resources