I've read a lot of the questions on stackoverflow about this, tried some examples and am still stuck why this won't work. So I am asking the community.
MODEL:
public class UploadModel
{
public string PatientID { get; set; }
public DateTime DrawDate { get; set; }
}
Controller:
public class FileManagementController : Controller
{
[HttpGet]
public ActionResult UpLoad()
{
ViewData["message"] = String.Empty;
UploadModel model = new UploadModel
{
PatientID = String.Empty,
DrawDate = DateTime.Now,
};
return View(model);
}
[HttpPost]
public ActionResult Upload(UploadModel model, HttpPostedFileBase MyFile)
{
if (ModelState.IsValid)
{
//Do Validation and Save here
}
UploadModel newmodel = new UploadModel
{
PatientID = model.PatientID,
DrawDate = model.DrawDate,
};
ViewData["message"] = "data submitted";
return View(newmodel);
}
View:
<form action="" method="post" enctype="multipart/form-data" id="MyForm">
#Html.EditorFor(m => m)
<label for="MyDateTime">My Date Time:</label>
<label for="MyFile">File:</label>
<input type="file" name="MyFile" id="MyFile" /><br />
<input id="submit" name="submit" type="submit" value="Save" />
</form>
From there, I have added to the _Layout.cshtml page the following code (which all maps correctly)
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery-ui-1.7.2.custom.css")" rel="stylesheet" type="text/css" />
<script src='#Href("~/Scripts/jquery-1.7.1.js")' type="text/javascript" ></script>
<script src='#Href("~/Scripts/jquery-ui-1.8.1.custom.min.js")' type="text/javascript" ></script>
<script type="text/javascript" src='#Href("~/Scripts/jquery.alphanumeric.pack.js")'></script>
<script type="text/javascript" src='#Href("~/Scripts/jquery.watermark.min.js")'></script>
Then in Views -> Shared I have added an EditorTemplates folder and have created a DateTime.cshtml page that has:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"),
new { #class = "date" })
<script type="text/javascript" >
$(document).ready(function () {
//set the date picker
var dtp = '#ViewData.TemplateInfo.GetFullHtmlFieldId("")';
dtp = dtp.replace("[", "_");
dtp = dtp.replace("]", "_");
//window.alert($(dtp).attr("value"));
var hid = ($(dtp).attr("type") == "hidden");
if (!hid) {
$(dtp).datepicker({
showOn: 'button', buttonImage: '#Href("~/Content/images/calendar.gif")%>', buttonImageOnly: true
, changeMonth: true, changeYear: true
, dateFormat: 'dd M yy'//, numberOfMonths: 2
});
}
});
</script>
This seems to be the flavor of most of the tutorials on this, but don't seem to work. No icon appears. In Chrome I get the html5 calendar popup but never the jquery one. Any suggestions at all would be greatly appreciated.
The selector looks incorrect to me. You're code:
var dtp = '#ViewData.TemplateInfo.GetFullHtmlFieldId("")';
Would result in a string: 'my_id', but you still need to tell jQuery that string is an ID, using the # symbol like so:
var dtp = '##ViewData.TemplateInfo.GetFullHtmlFieldId("")';
As a side note, do you really want to export that entire Script tag for each rendered DateTime in your model? Seems unnecessary to me, but you may have already thought about this. My recommendation would be to modify your DateTime.cshtml to simply:
#model DateTime
#Html.TextBox("", Model.ToString("dd/MM/yyyy"), new { #class = "date-picker" })
Then somewhere in your page or Layout, something like:
<script type="text/javascript" >
$(function () {
$('.date-picker').datepicker({
showOn: 'button', buttonImage: '#Href("~/Content/images/calendar.gif")%>', buttonImageOnly: true
, changeMonth: true, changeYear: true
, dateFormat: 'dd M yy'//, numberOfMonths: 2
});
});
</script>
That way, just one script is rendered and all your DateTime's are taken care of.
Since I'm a noob I can't post a comment (sorry!), but the only advice I can give is to make sure that the html derived from #Html.EditorFor(m => m) is exactly what you need (this html is different depending on the model). Here's more info about that: http://msdn.microsoft.com/en-us/library/ee402949(v=vs.98).aspx
Also, I noticed in the javascript section you have a %> at the end here: "#Href("~/Content/images/calendar.gif")%>" and it looks like an error.
Related
I'm still new to asp.net mvc, i want to delete list of partial view, the delete is working but i must reload the entire page to show the new list
What I want is the partial view show the new list after delete without load the entire page, so only the partial view is updated
Here is my code:
My view content some of partial view :
#model cc.Models.User
#{
Layout = "~/Views/Shared/_MemberLayout.cshtml";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")" type="text/javascript"></script>
<body class="container body-content">
<div id="partialView1">
#Html.Action(...)
</div>
<div id="partialView2">
#Html.Action(...)
</div>
<div id="partialView4">
#Html.Action(...)
</div>
<div id="partialView3" class="col-md-8 col-sm-1">
#Html.Action("UserHistory", "User")
</div>
</body>
Here is my partial view for UserHistory I tried to use ajax but it's not work. I already tried to use
$(this).closest('.historyRow').remove();
and
$("a.deleteHistory").live("click", function () {
$(this).parents("div.historyRow:first").remove();
return false;
});
Here is my code :
#model cc.Models.UserHistory
#{
Layout = null;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")" type="text/javascript"></script>
<div id="formHistory">
<div id="historyDetail">
<div id="editDataHistoryUser">
#foreach (var item in Model.History)
{
#Html.Partial("UserHistoryDetail", item)
}
</div>
#Html.ActionLink("Add Form", "AddUserHistory", null, new { id = "btnFormHistory" })
</div>
</div>
<script type="text/javascript">
$("#btnFormHistory").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editDataHistoryUser").append(html); }
});
return false;
});
$('#formHistory').on('click', '.deleteHistory', function () {
var id = $(this).data('id');
if (id == 0) {
$(this).closest('.historyRow').remove();
//$("a.deleteHistory").live("click", function () {
// $(this).parents("div.historyRow:first").remove();
// return false;
//});
} else {
var url = '#Url.Action("DeleteUserHistory", "User")';
$.post(url, { ID: id }, function (response) {
if (response) {
$(this).closest('.historyRow').remove();
//$("a.deleteHistory").live("click", function () {
// $(this).parents("div.historyRow:first").remove();
// return false;
//});
}
}).fail(function (response) {
});
}
});
</script>
Here is my UserHistoryDetail Code :
#model cc.Models.IUserHistory
#{
Layout = null;
}
<div id="formUserHistoryDetail">
#using (Ajax.BeginForm("UserHistoryDetail", "User", new AjaxOptions { HttpMethod = "POST" }))
{
<div id="historyRow">
<div>#Html.LabelFor(model => model.IDHistory, new { style = "display:none;" })</div>
...
delete
</div>
}
</div>
And here is my JsonResult when button delete clicked :
[HttpPost]
public JsonResult DeleteUserHistory(string ID)
{
db.delUserHistory(ID);
return Json(true);
}
I still cannot find the solution for this , or maybe i used ajax in wrong way, any suggestion?
Let's assume that the DeleteUserHistory post url is '/[Controller]/': '/UserHistory'
$('.deleteHistory').click(function(){
var url = '/UserHistory';
$.ajax({
type: "POST",
url: url,
data: data,
success: onSuccessCallback
});
});
What you should really do is use WebApi to manage data and use the views to display.
As for the delete, use method type 'delete' instead of 'post'. Post should be used for "adds".
SO i have this jquery template and i need to call a jquery or javascript function on the click of this anchor tag. Ive tried it a few different ways.
<a href="yourfunction()"
Ive tried
$('#number').click(function(e){
So if anyone could help it would be highly appreciated. The anchor tag in question is the phone number one with the id of number.
#model OpenRoad.Web.Areas.Marketing.Models.MobyNumberSelectionModel
#{
ViewBag.Title = "Moby Number Selection";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section scripts {
<script type ="text/javascript">
$('#number').click(function (e) {
alert('test');
});
});
mixpanel.track("View Marketing | Moby | Number Selection");
//$(document).on("click", "#number", function (e) {
// event.preventDefault();
// alert('test'); });
//$('#number').click(function (e) {
// Alert('test');
//});
</script>
}
<label class="lgform" style="text-align: left; padding: 10px 0;">Select state and area code:</label>
#Html.DropDownListFor(m => m.State, OpenRoad.Web.Helpers.DropDownLists.GetOptionValues("States", Model.State),
new { #class = "ddtrigger", data_url = "/Marketing/Moby/GetAreaCodes", data_template = "areaCodeTemplate", data_target = "AreaCode" })
#Html.DropDownListFor(m => m.AreaCode, (IEnumerable<SelectListItem>)ViewData["AreaCodes"],
new { #class = "ddtrigger", data_url = "/Marketing/Moby/GetPhoneNumbers",
data_template = "phoneNumberTemplate",
data_target = "phoneNumbers",
data_listtarget="true" })
#Html.HiddenFor(m => m.MobyNumber)
<script id="areaCodeTemplate" type="text/x-jquery-template">
<option value="${AreaCode}">${AreaCode}</option>
</script>
<br />
<script id="phoneNumberTemplate" type="text/x-jquery-template">
<div class="numberselectbox">
<strong>${FormattedPhoneNumber}</strong> Select<br/>
</div>
</script>
<div id="phoneNumbers">
</div>
Since you are using a template to generate the elements, these elements will be dynamic so you need to use delegated event model.
Also since it is a template, do not use static id for the elements since the elements can be duplicated - use class attribute instead
<script id="phoneNumberTemplate" type="text/x-jquery-template">
<div class="numberselectbox">
<strong>${FormattedPhoneNumber}</strong> Select<br/>
</div>
$(document).on('click', '.number', function(){
//do something
})
You could try jQuery's on() method or click() shorthand:
$(document).ready( function() {
$('#number').on('click', function(e){
// your method implementation here
e.preventDefault();
});
// OR //
$('#number').click(function(e){
// your method implementation here
e.preventDefault();
});
});
Using uploadify to auto submit a users files, in my controller method Request.Files["Name"] keeps returning null but request.form isn't null, I can see the file in request.form when I set a breakpoint and debug it. Am I missing something? I'm testing this on mvc2 but i plan on using it on mvc4.
<link href="../../Content/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="../../Scripts/jquery.uploadify.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#file_upload').uploadify({
'swf': '/Content/uploadify.swf',
'uploader': '/Home/UploadFile',
'auto': true
// Your options here
});
});
</script>
</head>
<body>
<%--<% using (Html.BeginForm("UploadFile", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>--%>
<input type="file" name="file_upload" id="file_upload" style="margin-bottom: 0px" />
<%-- <% } %>--%>
Controller Method:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
var theFile = Request.Files["file_upload"];
return Json("Success", JsonRequestBehavior.AllowGet);
}
If I add a submit button and then submit it it will work though. I need to be auto though without a submit button.
IIRC Uploadify uses fileData as parameter. So:
var theFile = Request.Files["fileData"];
or even better:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileData)
{
// The fileData parameter should normally contain the uploaded file
// so you don't need to be looking for it in Request.Files
return Json("Success", JsonRequestBehavior.AllowGet);
}
Of course if you are not happy with this name you could always customize it using the fileObjName setting.
I'm struggling to understand how to combine the TimePicker http://trentrichardson.com/examples/timepicker/ solution to my existing ASP.Net MVC3 C# site that uses DatePicker. DatePicker is currently working fine on it's own, but I need to add the time as well as the date, and TimePicker looks perfect for what I need, only I'm not sure how to implement it.
I see the example gives this code:
$('#example1').datetimepicker();
but I am unsure how to work it into my existing site / DatePicker function.
I have made sure I include these JS files in the HEAD section on the _Layout page, as well as adding the CSS to my existing DatePicker CSS file (jquery-ui-1.7.3.custom.css):
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.7.3.custom.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-timepicker-addon.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-sliderAccess.js")" type="text/javascript"></script>
and on my View page I have this code which displays the input and calls the DatePicker function (this works fine in its current form):
#model test.Models.News
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.News_Date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.News_Date, "News_Date", new { #ID = "News_Date" })
</div>
<p>
<input type="submit" value="Create" />
</p>
}
<script type="text/javascript">
$(document).ready(function () {
$("#News_Date").datepicker({
showOptions: { speed: 'fast' },
changeMonth: false,
changeYear: false,
dateFormat: 'dd/mm/yy',
gotoCurrent: true
});
});
</script>
I am unsure how to install the TimePicker function so it works with DatePicker on my MVC3 site.
I'd appreciate an explanation if someone wouldn't mind?
Many thanks.
You simply replace your datepicker call with datetimepicker in the view and provide the necessary arguments for both:
<script type="text/javascript">
$(document).ready(function () {
$('#News_Date').datetimepicker({
// Arguments for the date picker
showOptions: { speed: 'fast' },
changeMonth: false,
changeYear: false,
dateFormat: 'dd/mm/yy',
gotoCurrent: true,
// Arguments for the time picker
showSecond: true,
timeFormat: 'hh:mm:ss',
stepHour: 2,
stepMinute: 10,
stepSecond: 10
});
});
</script>
I have a project that I am working on, it's being developed in ASP.NET MVC2
Currently I have used Ajax to load some data. It works great on firefox and chrome however I have an issue with IE.
My controller:
public ActionResult UpdateSearchResults(FormCollection formValues)
{
var equipmentsResults = EquipmentQueries.GetEquipments(Request.Form["Voltage"],
Request.Form["EquipmentType"],
Request.Form["Word"]);
return PartialView("SearchResults", equipmentsResults);
}
My view:
<% using (Ajax.BeginForm("UpdateSearchResults",
new AjaxOptions {UpdateTargetId = "loadingData",
LoadingElementId = "loadingImage",
HttpMethod = "POST"}))
{ %>
<fieldset>
<legend>Filters</legend>
<label>Voltage: </label>
<%=Html.DropDownList("Voltage", (SelectList)ViewData["Voltage"], "Select Voltage", new { onchange = "this.form.submit();" })%>
<br />
<label>Equipment Type: </label>
<%=Html.DropDownList("EquipmentType", (SelectList)ViewData["Equipment"], "Select Equipment Type")%>
<br />
<label>Station Keyword Search: </label>
<%=Html.TextBox("Word")%>
<br />
<input id="btnSubmit" type="submit" value="Submit" name="submit" />
<br />
</fieldset>
<img id="loadingImage" src="../../Images/ajax-loader.gif" alt="loading"/>
<div id="loadingData"></div>
<% }%>
I have included the following scripts
<script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
What I found during debugging is that in chrome and firefox all the DropDownList populate the Request.Form ( Request.Form("Voltage") actually displays what the user has picked on the DropDownList), however in IE this Request.Form doesn't get populated at all, it's just an empty string...
Thanks for the help everyone
While I have no clue why your code doesn't work on IE I have some suggestions about improving it. So as usual we start by defining a view model which will represent the data we are dealing with on the view:
Model:
public class ProductViewModel
{
public string SelectedVoltage { get; set; }
public IEnumerable<SelectListItem> Voltages
{
get
{
return new SelectList(new[] {
new SelectListItem { Value = "110", Text = "110V" },
new SelectListItem { Value = "220", Text = "220V" },
}, "Value", "Text");
}
}
public string SelectedEquipementType { get; set; }
public IEnumerable<SelectListItem> EquipementTypes
{
get
{
return new SelectList(new[]
{
new SelectListItem { Value = "t1", Text = "Equipement type 1" },
new SelectListItem { Value = "t2", Text = "Equipement type 2" },
}, "Value", "Text");
}
}
public string Word { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new ProductViewModel());
}
[HttpPost]
public ActionResult Search(ProductViewModel product)
{
var equipmentsResults = EquipmentQueries.GetEquipments(product);
return View(equipmentsResults);
}
}
View:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<AppName.Models.ProductViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://github.com/malsup/form/raw/master/jquery.form.js"></script>
<!-- TODO: Put this in an external javascript file -->
<!-- I've left it here just to illustrate -->
<script type="text/javascript">
$(function () {
var options = {
success: function (result) {
$('#loadingData').html(result);
}
};
$('form').ajaxForm(options);
$('#SelectedVoltage').change(function () {
$('form').ajaxSubmit(options);
});
});
</script>
<% using (Html.BeginForm("search", "home")) { %>
<fieldset>
<legend>Filters</legend>
<label for="SelectedVoltage">Voltage: </label>
<%= Html.DropDownListFor(x => x.SelectedVoltage, Model.Voltages, "Select Voltage")%>
<br />
<label for="SelectedEquipementType">Equipment Type: </label>
<%= Html.DropDownListFor(x => x.SelectedEquipementType, Model.EquipementTypes, "Select Equipment Type")%>
<br />
<label for="Word">Station Keyword Search: </label>
<%= Html.TextBoxFor(x => x.Word)%>
<br />
<input id="btnSubmit" type="submit" value="Submit" name="submit" />
</fieldset>
<% } %>
<br />
<div id="loadingData"></div>
</asp:Content>
Now you can safely dump all the MSAjax* scripts as well as all Ajax.* helpers. Do it the proper way: unobtrusively, the jquery way.
How does the generated html look like for the select elements? Check if the select contains the 'name' attribute.
such as