how to handle partial view elements in javascript - javascript

please refer this code and it is for a partial view of my web application developed using mvc.
#model PortalModels.WholeSaleModelUser
#using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>WholeSaleModelUser</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</td>
</tr>
</table>
<div id="partial">
<table>
<tr>
<td>
<img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" />
</td>
</tr>
</table>
<script type="text/javascript">
function loadUserImage() {
var userImg = document.getElementById("blah");
var imgNm = $("#Name").value;
userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png";
alert(imgNm);
alert(userImg.src);
}
</script>
i need to handle the textchange event of this textbox in partial view using javascript code i have mentioned above
#Html.TextBoxFor(model => model.Name)
please somebody tell me how to handle the text change event of the above code line of textbox..

$document.on('blur', 'TextBox', function(){
//Do something
});
This format should work for any fields on a partial view. from here http://api.jquery.com/on/

Related

Pass the value of a button to a hidden field and save it to database

So my design is I have multiple display fields and one hidden field. Besides each row there are two buttons accept and reject.my point is when I click a button its value pass to the hidden field and submits automatically in the database.
when I try my code the button doesn't pass anything and I tried all the solutions related to this topic and nothing is working. what am I doing wrong?
controller:
[HttpGet]
public ActionResult Add_Fulfillment ()
{
var getData = db.TBL_Request.Include(x=>x.TBL_Accounts).Include(x=>x.TBL_Accounts_LOBs).ToList() ;
var add_fulfillment = new Add_Fulfillment();
var ful_ = new fulfillmentVM();
foreach (var data in getData)
{
List<Add_Fulfillment> fulfillment = db.TBL_Request.Select(i => new Add_Fulfillment
{
Request_ID = i.Request_ID,
Employee_no = i.Employee_no,
Operation_Date = i.Operation_Date,
Fulfillment_Rate = i.Fulfillment_Rate ??0,
Account_Name = i.TBL_Accounts.Account_Name,
LOB = i.TBL_Accounts_LOBs.LOB,
Status = i.Inserted_by
}).ToList();
ful_._Requests = fulfillment;
}
return View(ful_);
}
[HttpPost]
public ActionResult Add_Fulfillment_Accept(int Request_ID , int? Status)
{
var user= db.TBL_Request.Find(Request_ID);
//hiddenfieldvalue assigns it to the field in the database i want to update
db.SaveChanges();
return RedirectToAction("Add_Fulfillment");
}
[HttpPost]
public ActionResult Add_Fulfillment_Reject(int Request_ID)
{
return RedirectToAction("Add_Fulfillment");
}
the view
#model Staff_Requisition.Models.fulfillmentVM
#{
ViewBag.Title = "Add_Fulfillment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Add_Fulfillment</h2>
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Plain Page</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<table class="table">
<tr>
<th>
Employee_no
</th>
<th>
Operation_Date
</th>
<th>
Fulfillment_Rate
</th>
<th>
Account_Name
</th>
<th>
LOB
</th>
<th></th>
<th></th>
</tr>
#for (int i = 0; i < Model._Requests.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(x => Model._Requests[i].Employee_no)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Operation_Date)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Fulfillment_Rate)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Account_Name)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].LOB)
</td>
<td>
#Html.Hidden("Status" , Model._Requests[i].Status , new { id = "myEdit" })
</td>
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$("#btnAccept").click(function () {
$("#myEdit").val($("#btnAccept").val());
})
$("#btnReject").click(function () {
$("#myEdit").val($("#btnReject").val());
})
</script>
}
I solved it. the only issue was I didn't put the hidden field of the status inside the form .that's why it never passes the value. thank you for all your efforts though!
view:
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" onclick="accept(122)" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" onclick="reject(222)" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$('[name = "a_button"]').click(function () {
$('[name = "Status"]').val($('[name = "a_button"]').val());
})
$('[name = "button"]').click(function () {
$('[name = "Status"]').val($('[name = "button"]').val());
})
</script>

Ajax.BeginForm() Ajax Option Not Work in Razor View

Hi friend AjaxOption Not working in my Razor View
#using (Ajax.BeginForm("TestAvanceSearchRequisition", "Requisition",
new AjaxOptions
{
HttpMethod = "POST",
Confirm = "Do u Want to save",
UpdateTargetId = "divResponse"
}))
{
<table>
<tr>
<td class="lebelTD">
Date From:
</td>
<td class="fieldTD">
#Html.TextBox("requisition_from", "",
new
{
#class = "InputText",
onclick = "javascript:NewCssCal ('requisition_from','ddMMMyyyy','arrow','','','','')",
#style = "border-left:2px solid #FF3C3C;"
})
</td>
</tr>
<tr>
<td class="lebelTD">
Date To:
</td>
<td class="fieldTD">
#Html.TextBox("requisition_end_date", "",
new
{
#class = "InputText",
onclick = "javascript:NewCssCal ('requisition_end_date','ddMMMyyyy','arrow','','','','')",
#style = "border-left:2px solid #FF3C3C;"
})
</td>
</tr>
</table>
<table>
<tr>
<td align="right">
<input type="submit" class="smallbtn" />
</td>
</tr>
</table>
<div id="divResponse">
<table>
<tr>
<td class="lebelTD">Sales Total Amount</td>
<td class="fieldTD">
#Html.TextBox("Salesamt", #TempData["TotalSalesAmout"], new { #class = "InputText" })
</td>
</tr>
</table>
</div>
}
Not any Ajax Option not working. Like confirm box, Update Traget Id.. I had add all reference of Ajax.
Why not Ajax Option Not working. On button click go to Post method and get the result but no confirm box work and load full form.

Filter kendo dropdownlist to remove options

I want to filter security questions such that if I select questiona from the list of questions, for the next questions, I no longer see questiona in the list of security questions. This is to prevent duplicate selection of security questions.
Here's a jsfiddle with a pure jquery implementation:
http://jsfiddle.net/jbfbxvoo/
I was wondering how I can use the same approach to filter kendo dropdownlists:
E.g. I have three dropdownlists like:
<table style="float: left; width:300px;">
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q1Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion1", #class="security"})
.Name("Q1DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A1, new { #class = "formTextbox k-textbox", #id = "idAnswer1" })
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q2Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion2", #class="security" })
.Name("Q2DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A2, new { #class = "formTextbox k-textbox", #id = "idAnswer2" })
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q3Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion3", #class="security" })
.Name("Q3DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A3, new { #class = "formTextbox k-textbox", #id = "idAnswer3" })
</div>
</td>
</tr>
</table>
I tried this but doesn't work:
QuestionChanged: function () {
var sec = $('.security');
sec.change(function () {
sec.find('option').show().end().each(function () {
$('option[value="' + $(this).val() + '"]:not(:selected):not([value="0"])', sec).hide();
});
}).change();
}
For this implementation i have an idea, where first you need to have 3 dropdownlist that have one same datasource/observable but three different value to store each dropdownlist value and point to one same change event, example in mvvm
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd1, events:{change:onChange}" style="width: 400px;"/>
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd2, events:{change:onChange}" style="width: 400px;"/>
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd3, events:{change:onChange}" style="width: 400px;"/>
On the view model change event you do your logic, maybe you can write better code than mine right now but the main point is
To loop through all 3 dropdownlist <li></li> , and compare with the
three value dd1,dd2,dd3 hide if match, otherwise show it
And the code :
var dropdowns = $("input.customdropdownlist");
for(j=0;j<dropdowns.length;j++){
var list = $(dropdowns[j]).data("kendoDropDownList").ul.find("li.k-item");
for(i=0;i<list.length;i++){
if(viewModel.dd1 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd1).text){
$(list[i]).hide();
}else if(viewModel.dd2 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd2).text){
$(list[i]).hide();
}else if(viewModel.dd3 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd3).text){
$(list[i]).hide();
}else{
$(list[i]).show();
}
}
}
Working example in kendo dojo, add
updated dojo from modifying your code.
I have done something similar for kendo ComboBox. Do manipulate the below js function and it will work for kendo Drop Down also.
function QuestionChanged(event) {
$("[class^=security]").each(function () {
if (event.sender.element.attr('class') != $(this).attr('class')) {
var comboBox = $('#' + $(this).attr('id')).data('kendoComboBox');
$(comboBox.dataSource.data()).each(function () {
if (event.sender._selectedValue == this.Value) {
var data = this;
comboBox.dataSource.remove(data);
}
});
}
});
}
NOTE: Add security class to each of the drop down as security1 for first drop down, security2 for 2nd drop down and so on.
Hope it helps! Feel free to leave your feedback.

How to get text from a textbox using javascript

i have developed a web application using mvc4.
in this case i need to get a text box value(actually the text entered in the text box) using javascript.
here is the code i am using
#model PortalModels.WholeSaleModelUser
#using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>WholeSaleModelUser</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</td>
</tr>
</table>
<div id="partial">
<table>
<tr>
<td>
<img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" />
</td>
</tr>
</table>
<script type="text/javascript">
function loadUserImage() {
var userImg = document.getElementById("blah");
var imgNm = $("#Name").value;
userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png";
alert(imgNm);
alert(userImg.src);
}
</script>
in that case alert gives the value as "undefined" and if do the following modification alert gives nothing.
var imgNm = document.getElementById("Name").value;
for
var imgNm = $("#Name").value;
how to get the text entered in the text box?
You should use val() function for that:
var imgNm = $("#Name").val();
If you're using native javascript you should use this:
var userImgNameElement = document.getElementById("userImgNameId");
var userImgNameValue = userImgNameElement.getAttribute("value");
With "onChanged" event:
addEvent(document.getElementById('userImgNameId'), 'change', function(event) {
var userImgNameValue = event.target.getAttribute("value");
});
In an input element, the value of can be found in a value property of that element. It can therefore be retrieved via document.getElementById('idOfElement').value.
In an textarea element has it's value between the starting and the closing tag. Therefore, the value property is empty. In raw javascript, you would be able to retrieve the contents with document.getElementById('idOfElement').innerText.
If you are however using jQuery, Ufuk's solution with .val() is much easier to use.

Displaying details for master record using Javascript or jQuery in MVC4

I am trying to build a page with list of users. The goal is, that when you click "Details" link in the row, I would like to render partial view in the page using javascript or jQuery, So I dont need to reload the page. I have found many solutions (for example this), but I cant get it working, since I know next to nothing about javascript at the moment so I dont know how to connect what i found to code I have.
This is my partial view (i am not sure if it is correct as I wasnt able to even try to render it so far):
#model AdminDMS.Models.User
<h2>Details</h2>
<fieldset>
<legend>User</legend>
<div class="display-label">
#Html.DisplayNameFor(model => model.Guid)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Guid)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.TrusteeType)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.TrusteeType)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.Username)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Username)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.Email)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Email)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.LastLogin)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.LastLogin)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.PasswordChanged)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.PasswordChanged)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.IsUsingTempPassword)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.IsUsingTempPassword)
</div>
</fieldset>`
I am using async controller, these are my Details async actions:
public void DetailsAsync(Guid guid)
{
if (userList == null || DateTime.Now > lastUpdate.AddMinutes(5))
{
AsyncManager.OutstandingOperations.Increment();
client.GetUsersAsync();
lastUpdate = DateTime.Now;
AsyncManager.Parameters["guid"] = guid;
}
}
public ActionResult DetailsCompleted(IEnumerable<AdminDMS.Models.User> users)
{
if (userList == null || !userList.Equals(users))
userList = users.ToList<AdminDMS.Models.User>();
return PartialView("Details", users.Single(user => user.Guid == (Guid)AsyncManager.Parameters["guid"]));
}
And this is the view:
#model List<AdminDMS.Models.User>
#{
ViewBag.Title = "Users";
}
<h2>Users</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Guid
</th>
<th>
Username
</th>
<th>
Email
</th>
<th>
TrusteeType
</th>
<th>
Last Login
</th>
<th>
Last Password Change
</th>
<th>
Temporary Password
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Guid)
</td>
<td>
#Html.DisplayFor(modelItem => item.Username)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.TrusteeType)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastLogin)
</td>
<td>
#Html.DisplayFor(modelItem => item.PasswordChanged)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsUsingTempPassword)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { item.Guid }) |
#*#Html.ActionLink("Details", "Details", new { item.Guid })*# |
#Html.ActionLink("Delete", "Delete", new { item.Guid })
</td>
</tr>
}
</table>
<div class="detailsDiv">
</div>
I would like to replace that commented out action link with something, that will render the partial view in "detailsDiv" div that is left empty at the end.
Thanks in advance
UPDATE:
My controller now has this action
public PartialViewResult Details(Guid guid)
{
AdminDMS.Models.User user = null;
UserService.User serviceUser = client.GetUsers().Single(u => u.Guid == guid);
user = new AdminDMS.Models.User(serviceUser.Guid, serviceUser.TrusteeType, serviceUser.Username, serviceUser.Email, serviceUser.LastLogin, serviceUser.PasswordChanged, serviceUser.IsUsingTempPassword);
return PartialView("_detailsPartial", user);
}
_detailsPartial is the detail view (that hasnt changed at all)
this is the current call to controller in view:
#Ajax.ActionLink("Details", "Details", item, new AjaxOptions { UpdateTargetId = "detailsDiv", InsertionMode = InsertionMode.Replace})
This is the div I want to update:
<div id="detailsDiv">
</div>
There is nothing else in the view after this div.
Current result is that the link will open new page in the window and renders partial view (with item details as content)
I always use this to render a partial view with ajax, this works, if you have any other problems, it is something else :)
#Ajax.ActionLink("blabla", "DetailsCompleted", new { Users= "add users here" }, new AjaxOptions { UpdateTargetId = "detailsDiv"})
EDIT: CONTROLLER action
public PartialViewResult yourpartialname("data here")
{
"get your data
return PartialView(data);
}
EDIT 2:
You can do this:
#Ajax.ActionLink("Details", "Details", new {item = item.Guid}, new AjaxOptions { UpdateTargetId = "detailsDiv", InsertionMode = InsertionMode.Replace})
I know this will work, but I don't know if it's a big difference (I'm not that pro either :)), again, I don't know if its a big difference but you can change your partialview result to this:
public PartialViewResult DetailsPartial(Guid item)
{
AdminDMS.Models.User user = null;
UserService.User serviceUser = client.GetUsers().Single(u => u.Guid == guid);
user = new AdminDMS.Models.User(serviceUser.Guid, serviceUser.TrusteeType, serviceUser.Username, serviceUser.Email, serviceUser.LastLogin, serviceUser.PasswordChanged, serviceUser.IsUsingTempPassword);
return PartialView(user);
}
Where DetailsPartial is the name of your partial view
You can try this, I would do it this way, else I don't see any problems with your code
LAST EDIT
</footer>
#Scripts.Render("~/bundles/jquery")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#RenderSection("scripts", required: false)
</body>
</html>
I suppose the most appropriate thing to use for rendering just a part of the page is AJAX.
http://en.wikipedia.org/wiki/Ajax_(programming)
Honestely I'm not a pro in Asp.net but I suppose there is a tool kit that does the trick. http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/

Categories

Resources