Validation and submit button don't function together in PartialView while using a composite model - validation

Validation in my forms are defined in my Model.
If I don't include these two lines in my view:
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
The submit button works fine, but validation doesn't work. If I include these, validation starts working and the submit button doesn't work anymore.
I try to do the validation through my model.
My model:
public class TemplateDTO : DTOBase
{
public virtual int ID { get; set; }
[Required(ErrorMessage="فيلد ضروري")]
[RegularExpression("^[a-zA-z0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name { get; set; }
[RegularExpression("^[a-zA-zآ-ي0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name_Fr { get; set; }
public virtual IList<TemplateDetailsDTO> LstDetails { get; set; }
}
My composite model:
public class TemplateViewModel
{
public TemplateDTO Template { get; set; }
public List<TemplateFieldsDTO> TemplateFeilds { get; set; }
public int[] oSelectedFieldsDTO { get; set; }
public string Text { get; set; }
public bool NextLine { get; set; }
}
My Controller (ActionResult which calls the view and JsonResult which is the answer):
public ActionResult _NewTemplate()
{
if (myGlobalVariables.AllTemplateFieldsDTO == null)
{
TemplateFieldsClientService oTemplateFieldsClientService = new TemplateFieldsClientService();
myGlobalVariables.AllTemplateFieldsDTO = oTemplateFieldsClientService.GetAll();
}
TemplateDTO oTemplateDTO = new TemplateDTO();
oTemplateDTO.LstDetails = new List<TemplateDetailsDTO>();
TemplateViewModel x = new TemplateViewModel();
x.TemplateFeilds = myGlobalVariables.AllTemplateFieldsDTO;
x.Template = oTemplateDTO;
return PartialView(x);
}
[HttpPost]
public JsonResult _NewTemplate(TemplateViewModel oTemplateViewModel)
{
if (ModelState.IsValid)
{
if (oTemplateViewModel.Template != null)
{
if (oTemplateViewModel.Template.Name == null)
{
throw new System.ArgumentNullException("Parameter can not be null", "oTemplateDTO");
}
string strAttr = "";
if (oTemplateViewModel.NextLine)
strAttr = "\n";
List<TemplateDetailsDTO> LstTemDetails = new List<TemplateDetailsDTO>();
int Position = 0;
if (oTemplateViewModel.oSelectedFieldsDTO != null)
{
foreach (var i in oTemplateViewModel.oSelectedFieldsDTO)
{
TemplateDetailsDTO TempDetls = new TemplateDetailsDTO();
TempDetls.PositionNumber = ++Position;
TempDetls.Attributes = strAttr;
TemplateFieldsDTO OTemplateFieldsDTO = myGlobalVariables.AllTemplateFieldsDTO.Find(x => x.ID == i);
TempDetls.ObjFields = OTemplateFieldsDTO;
TempDetls.ObjTemplate = oTemplateViewModel.Template;
LstTemDetails.Add(TempDetls);
}
}
oTemplateViewModel.Template.LstDetails = LstTemDetails;
oTemplateClientService.AddNewTemplate(oTemplateViewModel.Template);
myGlobalVariables.AllTemplateDTO = oTemplateClientService.GetAllTemplate();
log.Info("Template added to Database.");
return Json(new { Result = "OK", Message = "عمليات ثبت با موفقيت انجام شد" }, JsonRequestBehavior.DenyGet);
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها ي ضروري را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
Code for my view:
#model IAC.SMS.MvcApp.Controllers.TemplateViewModel
<script type="text/javascript">
$(function () {
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
$('#btnAdd').click(function () {
$('#ListBoxSource').find('option:selected').appendTo('#oSelectedFieldsDTO');
})
$('#btnDelete').click(function () {
$('#oSelectedFieldsDTO').find('option:selected').appendTo('#ListBoxSource');
});
$('#btnUp').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var prevOption = $('#oSelectedFieldsDTO').find('option:selected').prev("option");
if ($(prevOption).text() != "") {
$(selectedOption).remove();
$(prevOption).before($(selectedOption));
}
});
$('#btnDown').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var nextOption = $('#oSelectedFieldsDTO').find('option:selected').next("option");
if ($(nextOption).text() != "") {
$(selectedOption).remove();
$(nextOption).after($(selectedOption));
}
});
});
function display() {
var dpt = document.getElementById("oSelectedFieldsDTO");
if (dpt.options[dpt.selectedIndex].text == "Text") {
document.getElementById("Text").disabled = false;
}
};
function SelectAllItems() {
$("#oSelectedFieldsDTO").each(function () {
$("#oSelectedFieldsDTO option").attr("selected", "selected");
});
};
//functions for ajax begin form
function Refresh() {
window.location.href = "#Url.Action("ListTemplate", "Template")" + "/";
}
function Success(data) {
if (data.Result == "OK") {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
Refresh();
}
else {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
}
function Fail() {
jSuccess(
'ارتباط برقرار نشد',
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
</script>
#using (Ajax.BeginForm("_NewTemplate", "Template", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "Success",
OnFailure = "Fail",
LoadingElementId = "Loading"
}, new { #id = "frmNewTemplate" }))
{
<table id="tblDetails" class="dataInput" style="width:500px;">
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مبدا
</label>
</td>
</tr>
<tr>
<td>
<label>
نام قالب
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name)
<label style="color:red; font-weight:bold;">*</label>
#Html.ValidationMessageFor(model => model.Template.Name)
</td>
<td></td>
<td rowspan="3">
#Html.ListBox("ListBoxSource", new SelectList(Model.TemplateFeilds, "ID", "Name", 1), new { size = 10 , style = "width:200px"})
</td>
</tr>
<tr>
<td>
<label>
توضيحات
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name_Fr)
</td>
</tr>
<tr>
<td>
<label>
پيام تکميلي
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Text , new { disabled="disabled"})
</td>
<td>
</td>
</tr>
<tr>
<td>
#Html.CH_CheckBoxFor(model=>model.NextLine, "خط بعد", false, false)
</td>
<td></td>
<td></td>
<td>
<button class="fixed button" id="btnAdd" type="button">اضافه<span class="left"></span> </button>
<button class="fixed button" id="btnDelete" type="button">حذف<span class="right"></span> </button>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مقصد
</label>
</td>
</tr>
<tr>
<td>
</td>
<td></td>
<td></td>
<td>
#Html.ListBoxFor(model => model.oSelectedFieldsDTO, new SelectList(Model.Template.LstDetails, "ID", "Name", 1), new { size = 10, style = "width:200px", onchange = "display()" })
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
</td>
<td>
<button class="fixed button" id="btnUp" type="button">بالا<span class="up"></span> </button>
<button class="fixed button" id="btnDown" type="button">پايين<span class="down"></span> </button>
</td>
</tr>
<tr>
<td>
#Html.HiddenFor(model=>model.Template.ID)
</td>
</tr>
</table>
<table>
<tr>
<td></td>
<td>
<div>
<button class="fixed button" type="submit" onmouseover="SelectAllItems()">ذخيره</button>
</div>
</td>
</tr>
</table>
}
Please tell me if I should include any more code.
My problem is that when I include the two lines code I mentioned above in my View to have validation, submit button in my PartialView won't function anymore, and the control doesn't go to the JsonResult function of my controller.
Thanks in Advance.

Update jquery.validate.min.js to version v1.12.0 - 4/1/2014 .
I hope you get the problem solved .

Related

.NET Core 6 Pull Down Menu Selection to Group through View Model

I am having partial success searching / grouping data through a viewmodel:
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Model
using System.ComponentModel.DataAnnotations; // Date Format
namespace Project01Name.Models
{
public class Class01Name
{
public int Id { get; set; }
public string? String01Name { get; set; }
public string? String02Name { get; set; }
public int? Int01Name { get; set; }
public bool? Bool01Name { get; set; }
[DataType(DataType.Date)]
public DateTime? DateTime01Name { get; set; }
}
}
**
View Model
**
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace Project01Name.Models.ViewModelsName
{
public class SearchByGroupName
{
public List<Class01Name>? Class01NameList { get; set; } // A list of movies.
public SelectList? String02NameSelection { get; set; } // A SelectList containing the list of genres. This allows the user to select a genre from the list.
public string? String02NameSelected { get; set; } // MovieGenre, which contains the selected genre.
public string? SearchString { get; set; } // SearchString, which contains the text users enter in the search text box.
}
}
Controller Action Method
// GET: String01Names
public async Task<IActionResult> Index2(string class01NameGroup, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> string02NameQuery = from m in _context.Class01Name
orderby m.String02Name
select m.String02Name;
var selectVariable = from m in _context.Class01Name
select m;
if (!string.IsNullOrEmpty(searchString))
{
selectVariable = selectVariable.Where(s => s.String01Name!.Contains(searchString));
}
if (!string.IsNullOrEmpty(class01NameGroup))
{
selectVariable = selectVariable.Where(x => x.String02Name == class01NameGroup);
}
var string02NameVM = new SearchByGroupName
{
String02NameSelection = new SelectList(await string02NameQuery.Distinct().ToListAsync()),
Class01NameList = await selectVariable.ToListAsync()
};
return View(string02NameVM);
}
View
#model Project01Name.Models.ViewModelsName.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" asp-items="Model.String02NameSelection"> <option value="">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" value="Filter" />
#*<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a> *#
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Not filtering data...simply changes pull down menu back to "All,"
displaying all data. Data not filtered.
**Question: ** What in the code has to be changed to have the data filtered successfully?
Well, seems you wanted to implement searching functionality in way, so that you can filter with the dropdown and search box and finally if you select All as dropdown value you want to load all the list without any filter and shorting means the full list which comes at first view.
If so, you need to use javascript for your dropdown change event as cshtml doesn't deal with change event. In addition, as you are using asp.net core MVC which would return HTML View altough, we need json data for Ajax reponse but we are would bee getting HTML View. So Ajax success Function will through an error where we would use filter with All parameter.
Modification Required:
Javascript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Note:
As you can see, in success function we are doing nothing, because it will always throuh an error because we are not returning json. Thus, we will work in error section. indow.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";. Here, for your understanding, we will call this function when we select All as our dropdown value in that scenario, we will pass All and nothing , nothing will convert into null and all will be our search key.
Modify Your Existing View:
In your existing view, replace blow dropdown code snippet , means the select items
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Note: If you notice I hav introduced a id id="allId" which will be using on dropdown change event.
Controller:
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Complete Demo:
Full Controller With Seed Model Class Value:
public class SearchController : Controller
{
public static List<Class01Name> listOfClass01Name = new List<Class01Name>()
{
new Class01Name() { Id =101, String01Name ="Titanic",String02Name = "Romantic", Int01Name =01, Bool01Name = false, DateTime01Name = new DateTime(2023-01-15) },
new Class01Name() { Id =102, String01Name ="Forest gump",String02Name = "Motivational", Int01Name =02, Bool01Name = true, DateTime01Name = new DateTime(2023-01-12) },
new Class01Name() { Id =103, String01Name ="Spider Man",String02Name = "Action", Int01Name =03, Bool01Name = false, DateTime01Name = new DateTime(2023-01-10) },
new Class01Name() { Id =104, String01Name ="Harry Potter",String02Name = "Suspense", Int01Name =04, Bool01Name = true, DateTime01Name = new DateTime(2023-01-13)},
};
public List<SelectListItem> String02NameSelectionList = new List<SelectListItem>()
{
new SelectListItem { Text = "Motivational", Value = "Motivational" },
new SelectListItem { Text = "Romantic", Value = "Romantic" },
new SelectListItem { Text = "Action", Value = "Action" },
new SelectListItem { Text = "Comedy", Value = "Comedy" }
};
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Full View:
#model DotNet6MVCWebApp.Controllers.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" name="searchString" />
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Output:

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

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

How can we use Web API through HttpClient?

I have used .NET API to consume it. But the code is not working. Can you please give me solution for the below code?
// State object
List<SelectListItem> state = new List<SelectListItem>();
// Client
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
// JSON type
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
// Web API controller
var response1 = client1.GetAsync("api/State");
if (response1.IsSuccessStatusCode) // Response type
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
return Json(state, JsonRequestBehavior.AllowGet);
[HttpGet]
public ActionResult Index()
{
List<Student> EmpInfo = new List<Student>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/StudentApi").Result;
if (response.IsSuccessStatusCode)
{
EmpInfo = JsonConvert.DeserializeObject<List<Student>>(response.Content.ReadAsStringAsync().Result);
return View(EmpInfo);
}
return View();
}
[HttpGet]
public PartialViewResult Edit(int id)
{
StudentViewModel EmpInfo = new StudentViewModel();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var responsecountry = client1.GetAsync("api/Country/").Result;
List<SelectListItem> country = new List<SelectListItem>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/StudentApi/" + id).Result;
if (response.IsSuccessStatusCode)
{
EmpInfo = JsonConvert.DeserializeObject<StudentViewModel>(response.Content.ReadAsStringAsync().Result);
if (responsecountry.IsSuccessStatusCode)
{
country = JsonConvert.DeserializeObject<List<SelectListItem>>(responsecountry.Content.ReadAsStringAsync().Result);
EmpInfo.Country = country;
}
return PartialView(EmpInfo);
}
return PartialView();
}
public ActionResult Create()
{
StudentViewModel student = new StudentViewModel();
List<SelectListItem> country = new List<SelectListItem>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/Country/").Result;
List<SelectListItem> state = new List<SelectListItem>();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
if (response.IsSuccessStatusCode)
{
country = JsonConvert.DeserializeObject<List<SelectListItem>>(response.Content.ReadAsStringAsync().Result);
student.Country = country;
var response1 = client1.GetAsync("api/State/" + Convert.ToInt32(country.FirstOrDefault().Value)).Result;
if (response1.IsSuccessStatusCode)
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
student.State = state;
}
}
return View(student);
}
public JsonResult GetStates(int countryId)
{
List<SelectListItem> state = new List<SelectListItem>();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response1 = client1.GetAsync("api/State/" + countryId).Result;
if (response1.IsSuccessStatusCode)
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
return Json(state, JsonRequestBehavior.AllowGet);
}
return Json(state);
}
[HttpPost]
public ActionResult Create(Student student)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("api/StudentApi", student).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return null;
}
[HttpPost]
public ActionResult Update(StudentViewModel student)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var stu = new Student()
{
Id = student.Id,
FirstName = student.FirstName,
LastName = student.LastName,
DateOfBirth = student.DateOfBirth,
Email = student.Email,
Phone = student.Phone,
CountryId = student.CountryId
};
HttpResponseMessage response = client.PutAsJsonAsync("api/StudentApi/", stu).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return null;
}
[HttpPost]
public JsonResult EmailExists(string email)
{
return Json(!String.Equals(email, "h#h.com", StringComparison.OrdinalIgnoreCase));
//var user = Membership.GetUser(UserName);
//return Json(user == null);
}
}
-----------
Create
-----------
#model Practice.Web.Models.StudentViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SignUp</title>
<script src="#Url.Content("~/Scripts/jquery-1.12.4.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#CountryId").change(function () {
$("#StateId").empty();
$.ajax({
type: 'GET',
url: '#Url.Action("GetStates")', // we are calling json method
dataType: 'json',
data: { countryId: $("#CountryId").val() },
success: function (state) {
//debugger;
$.each(state, function (i, s) {
$("#StateId").append('<option value="' + s.Value + '">' +
s.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
</head>
<body>
#using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
</tr>
<tr>
<td>First Name: </td>
<td>
#Html.TextBoxFor(m => m.FirstName)
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
#Html.TextBoxFor(m => m.LastName)
</td>
</tr>
<tr>
<td>Date Of Birth: </td>
<td>
#Html.TextBoxFor(m => m.DateOfBirth)
</td>
</tr>
<tr>
<td>Email: </td>
<td>
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(model => model.Email)
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
#Html.TextBoxFor(m => m.Phone)
</td>
</tr>
<tr>
<td>Country: </td>
<td>
#Html.DropDownListFor(m => m.CountryId, Model.Country)
</td>
</tr>
<tr>
<td>State: </td>
<td>
#Html.DropDownListFor(m => m.StateId, Model.State)
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
}
</body>
</html>
-----------------
Edit
---------------------
#model Practice.Web.Models.StudentViewModel
#{
ViewBag.Title = "Edit";
}
<style>
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {
border-radius: 2px;
}
.button2 {
border-radius: 4px;
}
.button3 {
border-radius: 8px;
}
.button4 {
border-radius: 12px;
}
.button5 {
border-radius: 50%;
}
</style>
<div class="modal-body">
#using (Ajax.BeginForm("Update", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divEmp" }))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
#Html.HiddenFor(m => m.Id)
</tr>
<tr>
<td>First Name: </td>
<td>
#Html.TextBoxFor(m => m.FirstName)
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
#Html.TextBoxFor(m => m.LastName)
</td>
</tr>
<tr>
<td>Date Of Birth: </td>
<td>
#Html.TextBoxFor(m => m.DateOfBirth)
</td>
</tr>
<tr>
<td>Email: </td>
<td>
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(model => model.Email)
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
#Html.TextBoxFor(m => m.Phone)
</td>
</tr>
<tr>
<td>Country: </td>
<td>
#Html.DropDownListFor(m => m.CountryId, Model.Country, new SelectListItem { Value = Model.CountryId.ToString() })
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" id="btnHideModal" /></td>
</tr>
</table>
}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Update</button>
<button type="button" class="btn btn-primary button button4">
Hide
</button>
</div>
<script type="text/javascript">
$(document).ready(function () {
//$("#btnShowModal").click(function () {
$("#loginModal").modal('show');
//});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>
----------------------
Edit
---------------------
#model IEnumerable<Practice.Entity.Student>
#{
ViewBag.Title = "Index";
}
<html>
<head>
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
#*<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/themes/base/jquery-ui.min.css") rel=" stylesheet" type="text/css" />
<script>
$(document).ready(function () {
//$(".editDialog").live("click", function (e) {
$(".editDialog").click(function (e) {
debugger;
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Employee Detail',
autoOpen: false,
resizable: false,
height: 455,
width: 550,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
debugger;
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
}
});
$("#dialog-edit").dialog('open');
return false;
});
});
</script>*#
</head>
<body id="divEmp">
<h2>Index</h2>
#Html.ActionLink("Create Student", "Create", "Student")
<div id="dialog-edit">
</div>
<table>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>DOB</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.DateOfBirth</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = #item.Id }, new { #class = "editDialog" })*#
<a class="editDialog">Edit</a>
</td>
</tr>
}
</table>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">Satya Login</h4>
<div id="divHtml"></div>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".editDialog").click(function () {
$("#loginModal").modal('show');
$.ajax({
url: '/Student/Edit/1',
contentType: 'application/html; charset=utf-8',
type: 'GET'
})
.success(function (result) {
$('#divHtml').html(result);
})
.error(function (xhr, status) {
alert(status);
});
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>

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