In a view, there's a DisplayFor tied to a DateTime field in the Model. To update the field, an AJAX call returns a Date. I can convert the AJAX date into a MM/DD/YYYY value, but setting the DisplayFor with a .val doesn't update the view. Chrome Developer Tools shows no error, and in fact shows the correct converted DateTime, but the DisplayFor doesn't update. I haven't tried changing the .attr instead of the .val because it seems like .val would be the correct option. Can anyone see why the view isn't updating? Thanks in advance!
Model declaration:
DateTime? SaleDate { get; set; }
DisplayFor in View:
#Html.LabelFor(m => m.SaleDate, "Sale Date")
#Html.DisplayFor(m => m.SaleDate, "{0:d}", new { #class = "form-control" })
Update script inside successful AJAX call:
success: function (data) {
var $sDate = $("#SaleDate");
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(data[0].SaleDate);
var dt = new Date(parseFloat(results[1]));
$sDate.val(dt); //dt is correct Date, but DisplayFor isn't updating!
}
EDIT
The page source indicates that the id is correct, but there's no input. I assume this is because of a DisplayFor vs. a TextBoxFor, but could the apparent absence of an id be the problem?
<label for="SaleDate">Sale Date</label>
6/1/2016 12:00:00 AM//no input section, just the DateTime value
Or, if SaleDate is null:
<label for="SaleDate">Sale Date</label>
//no value or input section
The Razor code in the View produces some HTML code. Javascript works on client side and has no idea about Razor's #Html.DisplayFor, only about its output. I'm not strong in Razor so my offer can contain errors.
1. #Html.TextBoxFor(m => m.SaleDate, "{0:d}", new { #class = "form-control", id = "SaleDate" }).
JS remains the same. Con: This is editable textbox (input)
2. <span id="SaleDate" class="form-control">#Html.DisplayFor(m => m.SaleDate, "{0:d}")</span>
JS last line should be $sDate.html(dt);
I hope it helps.
Related
In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?
Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});
I have an ASP.NET MVC application where I have a textbox with a jquery datePicker and a HTML.ActionLink that will download an Excel document that uses the date string picked from the datePicker. I want the link to the Excel download to use this date string as a parameter in its query string.
In the example code I will provide sample names for my classes and variables.
Here is an excerpt from my main view (View is named "TestView", Model is of class "TestModel"):
#using (Ajax.BeginForm("TestForm", FormMethod.Post,
new AjaxOptions
{
UpdateTargetId = "IdSomething",
OnFailure = "handleFailure(xhr, status, 'IdSomething')"
}))
{
#Html.AntiForgeryToken()
#Html.Action("TestSettings", Model)
<div class="clear margin-bottom-adjusted">
#Html.ActionLink(Markup.Download_As_Microsoft_Excel, "Download",
new { InstantlyUpdatedDate = Model.InstantlyUpdatedDate },
new { #class = "download-excel" });
</div>
}
Here is the relevant excerpt from the "TestSettings" view(it also uses a model of the class "TestModel"). The submit button here and the variable "NotInstantlyUpdatedDate" are used for updating a graph, but this should not be relevant for the Excel download:
<div>
#Html.TextBoxFor(m => m.NotInstantlyUpdatedDate, new { #class =
"datepicker", #onchange = "setExcelDownloadDate(" + #Json.Encode(Model) +
", $(this))" })
<input type="submit" value="#Markup.Update" class="btn" />
</div>
The "setExcelDownloadDate" function is defined in javascript like this:
function setExcelDOwnloadDate(model, item) {
if (item.attr('name') === "NotInstantlyUpdatedDate")
model.InstantlyUpdatedDate = item.val();
$.ajax({
url: '../Test/UpdateTestView',
type: 'post',
data: {
model: model
}
});
}
Relevant excerpt from my Controller:
public TestController
{
//Should only get called once by another view
[HttpPost]
public ActionResult InitTestView(TestModel model)
{
model.NotInstantlyUpdatedDate = "2018, 01, 01";
model.InstantlyUpdatedDate = model.NotInstantlyUpdatedDate;
return PartialView("TestView", model);
}
[HttpPost]
public ActionResult UpdateTestView(TestModel model)
{
return PartialView("TestView", model);
}
[HttpPost]
public Task<ActionResult> Download(DownloadModel model)
{
//download the model here
}
}
Here is my "TestModel" class for this example:
[Serializable]
public class TestModel
{
public string NotInstantlyUpdatedDate { get; set; }
public string InstantlyUpdatedDate { get; set; }
}
And here is my DownloadModel class:
public class DownloadModel
{
public string InstantlyUpdatedDate { get; set; }
}
OK, thank you for bearing with me. Here is what's happening:
First the InitTestView method is called, and it renders a TestView. If I place a breakpoint at the #Html.ActionLink line in the TestView, it will show me that the model.InstantlyUpdatedDate variable is "2018, 01, 01" (this is correct and the expected behaviour).
Since the TestSettings view is embedded in the TestView, it will render the Html.TextBoxFor for my datepicker. If I now inspect the Download button in my browser, a correct download query string will show, with the date "2018, 01, 01" as a parameter.
Now, let's say I pick the date ("2018, 01, 02") from the datepicker (the conversion to a date string is done in jquery, don't worry about this as it's working as expected). This date will now show in the textbox, and the #onchange event will trigger my javascript function setExcelDownloadDate. In this method, I can put breakpoints and see that my model.InstantlyUpdatedDate has indeed been set to "2018, 01, 02". This is the correct behaviour.
From the javascript function the ajax call sends the model object to my TestController. If I break in the function UpdateTestView, I can look at my model variable and also see here that the value has changed to "2018, 01, 02". Working correctly.
Now that this method returns a new instance of my TestView with the updated model, I can still break at the Html.ActionLink line and see that yes indeed, the Model.InstantlyUpdatedDate is "2018, 01, 02", which is correct.
However, here comes the problem. If i inspect the link in my browser, I will see that the url is incorrect. The date is not "2018, 01, 02", but still "2018, 01, 01". If I click the link and put a breakpoint in my Download method, the model's InstantlyUpdatedDate property will also be "2018, 01, 01" instead of "2018, 01, 02".
For some reason the model property InstantlyUpdatedDate seems to change back to it's original value. I do not know why this happens, and therefore I ask if some of you may be able to help me. This is part of a larger codebase, and something I don't know about might of course screw with what's happening. It could also be that this is the expected behaviour for some reason, and that I'm just not familiar enough with how this should work.
Thank you for your time.
I have a bit of trouble following this but I'll give a try. It seems like you aren't doing anything with the result of $.ajax. It will return the partial view with everything filled up but nothing is done with it.
$.ajax({
url: '../Test/UpdateTestView',
type: 'post',
data: {
model: model
}
}).done(function( html ) {
// $( "#results" ).append( html ); // Put the html somewhere
});
Personally, in the onchange, I would just update the link instead of the whole partial view. I usually update the partial view when there's a bit more changes than just a link.
$('#linkId').attr('href', '#Url.Action(Markup.Download_As_Microsoft_Excel, "Download")?InstantlyUpdatedDate=' + item.val());
I'm working on a project with ASP.NET MVC, using Razor. Once the form finishes loading on the page, I expect the user triggers .on ('change') in an input. Once this happens, an AJAX call is executed, returning the user's data, disabling and filling the inputs that are linked to the properties of a model that starts empty (when the page is loaded).
The data is filling up without problems, but when I send it back to the controller to be processed, the values that correspond to the inputs that were filled after the AJAX execution arrive as null.
<div class="form-label-group col-md-4 mb-3">
#Html.LabelFor(model => model.AttendeeName, new { #class = "upside-label", #for = "firstName" })
#Html.EditorFor(model => model.AttendeeName, new { htmlAttributes = new { #class = "form-control", #id = "firstName", #placeholder = Resources.ResourcesPerson.PlaceholderPersonName } })
#Html.LabelFor(model => model.AttendeeName, new { #class = "downside-label", #for = "firstName" })
<div class="text-danger">
#Html.ValidationMessageFor(model => model.AttendeeName)
</div>
</div>
I have tried the following without success:
$("input[name=AttendeeName]").attr('disabled', true);
$("input[name=AttendeeName]").val(data.AttendeeName).change()
Thank you for your assistance.
This is expected behaviour. disabled elements are not sent in form data.
If you still want those values to be sent, don't disable the fields. Possibly try readonly instead, assuming that you don't want users to edit the fields:
$('input[name="AttendeeName"]').prop('readonly', true);
Hi i want to do update operation for show and hide div in mvc5 . I will explain my issue with example.
This is my view. In this view i have one field called VisitType. If i clcik the Visit Type as DirectVisit the StartTime and EndTime field will be show(visible) othesewise it will be hide mode.
My Model (Visistors View Mode)
public bool VisitType { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
My View
<div class="col-sm-4" id="VisitType">
<div class="form-group">
<span style="color: #f00">*</span>
#Html.Label("Visit Type", new { #class = "control-label" })
<label>
#Html.RadioButtonFor(model => model.VisitType, "true", new { id = "" }) Telephone
</label>
<label>
#Html.RadioButtonFor(model => model.VisitType, "false", new { id = "" }) Direct Visit
</label>
</div>
</div>
<div id="StartTime">
<div class="col-sm-3">
<div class="foem-group">
#Html.Label("Start Time", new { #class = "control-label" })
#Html.TextBoxFor(model => model.StartTime, new { #class = "form-control ", type = "text" })
#Html.ValidationMessageFor(model => model.StartTime)
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.Label("End Time", new { #class = "control-label" })
#Html.TextBoxFor(model => model.EndTime, new { #class = "form-control ", type = "text" })
#Html.ValidationMessageFor(model => model.EndTime)
</div>
</div>
</div>
My Jquery code
$(document).ready(function () {
$('#StartTime').hide();
$('#VisitType input[type="radio"]').change(function () {
if ($(this).val() === 'false') {
$('#StartTime').show();
}
else {
$('#StartTime').hide();
}
});
});
Now what i want is if i put one entry in my application by selecting the VisitType as Direct Visit and enter StartTime and EndTime ans Saved it. Now i want to change the VisitType as Telephone. So i click the Edit button and once it open the view it have to pass the value to Visit type radio button and also Start Time and end time time also need to be visible with values.
I passed the value to radio buttons in edit mode. But i donno hoe to visible the StartTime and EndTime in edit mode. I donno the exact j-query code. This is the issue. Please any one help me to resolve this issue.
The Code which i tried
Contrroller Code
public ActionResult Edit(Guid ?id)
{
WafeERP_NEWEntities db = new WafeERP_NEWEntities();
VisitorsViewModel objvisitorsviewmodel = new VisitorsViewModel();
View_VisitorsForm objviewvisitorsForm = db.View_VisitorsForm.Find(id);
if (objviewvisitorsForm.VisitType== true)
{
objvisitorsviewmodel.VisitType= true;
}
else
{
objvisitorsviewmodel.VisitType= false;
}
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "DisplayName", objviewvisitorsForm.EmployeeID);
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "DisplayName", objviewvisitorsForm.CustomerID);
objvisitorsviewmodel.VisitingID = objviewvisitorsForm.VisitingID;
objvisitorsviewmodel.Date = objviewvisitorsForm.VisitingDate;
objvisitorsviewmodel.VisitType= objvisitorsviewmodel.VisitType;
return View(objvisitorsviewmodel);
}
This code pass fetch the value from db and pass it to radio button correctly but now i want to show the starttime and endtime field with values once the view got open by clicking edit button. I tried my level best to explain the issue please any one help me to resolve this issue.
Advance thanks..
You should start by first wrapping the elements in a <div> so that you can show and hide them all rather than having to select all the associated labels, textboxes and validation message placeholders
<div id="date-controls">
#Html.LabelFor(m => m.StartTime)
#Html.TextBoxFor(m => m.STartTime)
....
</div>
and use css to initially hide them
#date-controls {
display:none;
}
then to display them initially if the value of VisitType is true, add the following script
var isVisit = '#Model.ContactMethod';
var dateControls = $('#date-controls');
if (isVisit == 'True') {
dateControls.show();
}
and also modify the script handling the radio buttons to
$('#VisitType input[type="radio"]').change(function () {
var selected = $('#VisitType input[type="radio"]:checked').val();
if (selected == 'true') {
dateControls.show();
} else {
dateControls.hide();
}
});
Side note: Your VisitType property should not be a bool. A bool should only be used for a property to which the answer can only be Yes or No, and the answer to What is the method of contacting us is not Yes or No, its by Telephone, or by Attending a meeting etc. By using a bool it also means that you have no flexibility to add other types in the future (your client might want to offer home visits to incapacitated people, or the option of video conferencing). Instead your property should be a collection or an enum.
Problem Statement: I want to change the display name of labels(#Html.LabelFor) in Razor view of MVC based on the display names which i get from db.
I have added the dropdown list of languages in the _Layout.cshtml
<li>#Html.Action("Index", "LanguageDropdown", new { languageid = Request["languageId"] })</li>
I have created one partial view for drop down:
#model ALCMS.Web.Models.Master_or_Configuration.LanguageDropdownModel
<script type="text/javascript">
function GetLanguage() {
var languageId = $('#LanguageId').val();
var Url = "#Url.Content("~/MasterConfigGeneral/GetLanguage")";
$.ajax({
url: Url,
dataType: 'json',
data: { LanguageId: languageId },
success: function (data) {
}
});
}
</script>
<div style="display:inline-block">
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })
</div>
Partial View Controller:
public ActionResult Index(string languageId)
{
//return View();
var languages = dbEntity.LookupLanguages;
var model = new LanguageDropdownModel
{
LanguageID = languageId,
Languages = languages.ToList().Select(l => new SelectListItem
{
Value = Convert.ToString(l.LanguageID),
Text = l.Name
})
};
return PartialView(model);
}
In Controller Json Result method:
public JsonResult GetLanguage(int languageID)
{
JsonResult jsResult = new JsonResult();
objdbGlobalTenant.ddlLanguage = (from lsr in dbEntity.LocaleStringResources
where lsr.LanguageID == languageID
select new SelectListItem()
{
Text = lsr.ResourceValue,
Value = lsr.ResourceName
}).Distinct().ToList<SelectListItem>();
//ViewBag.Language = objdbGlobalTenant.ddlLanguage;
jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsResult;
}
Now everything is working fine.I'm able to get the selected langaugeID in Json Result method in Controller based on the change event of Language dropdown. Based on this Language ID i'm getting display names(ResourceValue) which i need to apply for the particular view.
Problems:
1>After getting the display names from db how to change display names
of particular view when language change event triggers.?? For
ex:Currently i'm seeing the Create.CSHTML. Now if i change the
language dropdown it should trigger Json Event in controller and
after getting values it should apply the values on the view which it
got from db.
Note: Dropdown is in Layout.cshtml(like master in .aspx)
2>Drop-down which i placed in Layout.cshtml is getting refreshed
every time new view is loaded which inherits(layout.cshtml).How to
make the controller to retain it's state during postback??
3>How to get the selected drop-down item from the layout in multiple
Controllers,to change the display name in each view based on the langaugeid
of dropdown in layout
How to do this??If i'm doing wrong suggest me some other ways...
Below are the suggestions :
Issue 1 :
You may keep one attribute in each label which identifies them uniquely.
Your HTML should render like following
<!-- For English -->
<label label-unique-name="Name">Name</label>
<label label-unique-name="Surname">Surname</label>
<!-- For French -->
<label label-unique-name="Name">nom</label>
<label label-unique-name="Surname">nom de famille</label>
<!-- For Spanish -->
<label label-unique-name="Name">nombre</label>
<label label-unique-name="Surname">apellido</label>
Here label-unique-name is your attribute, which will remain fixed for each language. Now when you change the language from dropdown you will bring the values like below.
<!-- For English -->
<label-unique-name:"Name",label-value:"Name">;<label-unique-name:"Surname",label-value:"Surname">
<!-- For French -->
<label-unique-name:"Name",label-value:"nom">;<label-unique-name:"Surname",label-value:"nom de famille">
<!-- For English -->
<label-unique-name:"Name",label-value:"nombre">;<label-unique-name:"Surname",label-value:"apellido">
Please note : this is for understanding only, it's not a JSON.
Now using jQuery go through each label and replace the label's value. Hope it'll help you.
Issue 2 :
You can save the selected language's value in session, and generate your dropdown accordingly.
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), !string.isNullorEmpty(HttpContext.Current.Sessions["Language"]) ? HttpContext.Current.Sessions["Language"] : "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })