Fill control with another MVC - c#

I have experience in C#, but don't have any in Javascript.
What I want to achieve shouldn't be that hard, but I just can't get it to work:
I want to fill the text property of a label with the text property of a textbox.
This needs to be done at the KeyUpEvent.
I already created the KeyUpEvent and it is working, but it doesn't fill my label's text property using the following code:
<script type="text/javascript">
$(document).ready(function ()
{
$("##Html.FieldIdFor(model => model.Quantity)").keyup(OnQuantityChanged);
});
function OnQuantityChanged()
{
alert("onQuantityChanged event fired.")
document.getElementById('##Html.FieldIdFor(model => model.SubTotalExclTax)').value = document.getelementById('##Html.FieldIdFor(model => model.UnitPriceExclTax)').value
}
</script>
So I create a function called OnQuantityChanged() and I call this function on KeyUp event.
The alert in my function: alert("onQuantityChanged event fired.") gets called and shows me a dialog, so the function does get called.
I'm using #Html.FieldIdFor, for getting the id of the control. I think this is implemented by NopCommerce and down here is the definition of the FieldIdFor method:
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
I think I made a syntax error, but don't know how to debug Javascript, since setting a breakpoint in Visual Studio(2012), doesn't pause the code.
I think the line below has some incorrect syntax, correct me if i'm wrong:
document.getElementById('##Html.FieldIdFor(model => model.SubTotalExclTax)').value = document.getelementById('##Html.FieldIdFor(model => model.UnitPriceExclTax)').value
Update
HTML of page is below:
<table>
<tr>
<td>
#Html.NopLabelFor(model => model.UnitPriceInclTax):
</td>
<td>
#Html.EditorFor(model => model.UnitPriceInclTax)#Model.UnitPriceInclTax
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.UnitPriceExclTax):
</td>
<td>
#Html.EditorFor(model => model.UnitPriceExclTax)#Model.UnitPriceExclTax
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.Quantity):
</td>
<td colspan="2">
#Html.EditorFor(model => model.Quantity, new { id = "lblQuantity"})
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.SubTotalInclTax):
</td>
<td>
#Html.EditorFor(model => model.SubTotalInclTax)#Model.SubTotalInclTax
</td>
</tr>
<tr>
<td>
#Html.NopLabelFor(model => model.SubTotalExclTax):
</td>
<td>
#Html.EditorFor(model => model.SubTotalExclTax)#Model.SubTotalExclTax
</td>
</tr>
</table>

You don't need # when using document.getElementById just string representing id is enough.
There is no value of a label you could just set innerText property.
Pure javascript solution:
document.getElementById("YourID").innerText = "New Text";
JQuery Solution
$("#YourID").text("New Text");

That part of server side code is not executed by ASP.NET since it is inside a string. You can resole using a variable to store the id:
var subTotalId = #Html.FieldIdFor(model => model.SubTotalExclTax);
and then use the subTotalId in your javascript (given that Html.FieldIdFor return the id of the element.
A better way is to use only javascript, with ASP.NET MVC you should know the ids of the DOM elements, so why do you need to find them at runtime?
Why not using Jquery:
$('#IdOfSubTotalElement').val();

Related

how can i get current model item in mvc

I have this list view that include edit button leads to modal
<table class="table" id="table">
#foreach (var item in Model.model2)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.who_reply)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.DisplayFor(modelItem => item.Details)
</td>
<td>
#Html.DisplayFor(modelItem => item.Reply_Id)
</td>
<td>
<input class="edit" id="edit" type="button" value="edit" data-reply="#item.Details" data-Reply_Id="#item.Reply_Id" />
</td>
</tr>
}
</table>
I wrote this jquery code to check Reply_Id value it works fine it gives me the current Reply_Id
$('.edit').click(function () {
alert($(this).data('Reply_Id'));
$('#ModalPopUp6').modal({ backdrop: 'static', keyboard: false });
$("#reply-text6").val($(this).data('reply'));
});
but the problem is that when I press save button in modal only get the first reply_id not the current:
$("#save").click(function () {
alert($('.edit').data('Reply_Id'));
});
Your issue is caused by
$(".class").data(dataname)
which retrieves the first entry, you need to "store" which edit button (reply_id) was clicked - either in a simple variable or in a more robust method such as:
$('.edit').click(function () {
// get the edit button's ID
var id = $(this).data('Reply_Id');
// store it against the modal
$('#ModalPopUp6').data("replyid", id);
$('#ModalPopUp6').modal({ backdrop: 'static', keyboard: false });
$("#reply-text6").val($(this).data('reply'));
});
then
$("#save").click(function () {
// get the original row's ID from the modal
var id = $('#ModalPopUp6').data("replyid");
// find the matching button (then get the parent row for the whole record)
var row = $("[data-Reply_id=" + id + "]").closest("tr");
});

Why I can't pass this model to a controller in ASP.NET MVC [duplicate]

This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 6 years ago.
Why i can't pass this model to a controller in ASP.NET MVC?
This is my View:
#model Pro.WebUI.ViewModels.DataItemVm
<div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstSetList.FirstOrDefault().Name)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstSetList.FirstOrDefault().Amount)
</th>
</tr>
#foreach (var item in Model.FirstSetList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Amount)
</td>
</tr>
}
</table>
<hr/>
<div>
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.FirstSetList)
<input type="submit" value="Confirm"/>
}
</div>
</div>
After I click Confirm button - this method receives model with Count = 0;
public ActionResult FirstSet(DataItemVm model)
{
...
}
Of course my ViewModel DataItemVm has list:
public class DataItemVm
{
public List<FirstSetViewModel> FirstSetList { get; set; }
}
So it looks like that problem is only at view. Maybe BeginForm should be in other place? However HiddenFor should send be enough to send this model.
Change #foreach cycle to for - ASP.NET MVC uses indexers to generate correct ids and names for elements, so you should use #Html.TextBoxFor(x=>x.Array[index]) to correctly generate html for your collections.
This cycle:
#foreach (var item in Model.FirstSetList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.TextBoxFor(modelItem => item.Amount)
</td>
</tr>
}
Should instead look like this:
#for (var i = 0; i < Model.FirstSetList.Length; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model.FirstSetList[i].Name)
#Html.HiddenFor(model => model.FirstSetList[i].Name) //otherwise name won't be returned to controller
</td>
<td>
#Html.TextBoxFor(model=> model.FirstSetList[i].Amount)
</td>
</tr>
}
Another issue is - markup for the data that you want to be sent to the controller should be put inside #using (Html.BeginForm()){//put it here} block.
Check out this post about model binding in ASP.NET MVC:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

Javascript string formatting

In my C# webapplication, I have to pass this below html string to a client side function by clicking on a server side button code. I am using Firefox browser.
htmlString is:
<div id='divPopUpToXyz.abc#def.com'>
<table>
<tr>
<td>
<img width='10' src='../images/cross.gif' onclick='deleteDiv(1,'ToXyz.abc#def.com','To')>
</td>
<td>
Xyz.abc#def.com
</td>
</tr>
</table>
</div>
On server side i am using this to call the required JS function:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "returnValue('" + htmlString+ "');", true);
But I am getting an error like this:
"missing ) after argument list"
I checked through firebug, and found that the htmlstring gets distorted like this:
<div id='divPopUpToXyz.abc#def.com'>
<table>
<tbody>
<tr>
<td>
<img src="../images/cross.gif" onclick="deleteDiv(1," toXyz.abc#def.com','to')="" width="10">
</td>
<td>
Xyz.abc#def.com
</td>
</tr>
</tbody>
</table>
</div>
I am not getting why it is changing like this.
Please suggest some way out.
you are not passing the value you expect to be passing
onclick='deleteDiv(1,'ToXyz.abc#def.com','To'
is interpreted as two attributes
onclick='deleteDiv(1,'
ToXyz.abc#def.com','To'=""
because of the first ' following 1, is terminating the onclick attribute assignment
change the htmlString assignement to
var htmlString = HttpUtility.JavaScriptStringEncode(#"<div id='divPopUpToXyz.abc#def.com'><table><tr><td><img width='10' src='../images
/cross.gif' onclick='deleteDiv(1,""ToXyz.abc#def.com"",""To"")'>
</td><td>Xyz.abc#def.com</td>
</tr></table></div>");
and you should be good to go

KendoUI MVC grid pop-up , how to return the value of selected combobox item

i am new to Kendo UI as well as javascript.Using MVC Kendo grid editing with Pop-up mode.I created custom template page(under EditorTemplates folder) for editing when pop-up window opens.There are some textboxes and Kendo Combobox widgets in that page to update records.
Values that coming from textboxes can be send to controller but selected item's value on combobox couldn't be send to controller.How can i do that?
View(Razor)
#model PROJECT.UI.WebService.Proxy.DSrvINFO.PERSONALINFORMATIONS
<div class="row">
<div class="span10">
<div style="overflow-y:scroll;overflow-x:hidden;height: 500px;" >
<table width="100%" cellspacing="5" style="margin: 20px">
<tr>
<td width="10%">
#Html.LabelFor(model => model.NAME)
</td>
<td width="40%">#Html.EditorFor(model => model.NAME)
</td>
<td width="10%">
#Html.LabelFor(model => model.SURNAME)
</td>
<td width="40%">#Html.EditorFor(model => model.SURNAME) </td>
<td width="10%">
#Html.LabelFor(model => model.IDTYPE)
</td>
<td width="40%">
#(Html.Kendo().ComboBox()
.Name("IDTYPES")
.DataTextField("DESCRIPTION").HtmlAttributes(new { style="width:220px"}) /
.DataValueField("REFERENCEID")
// .Filter(FilterType.Contains)
.Placeholder("SELECT")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Details", "Items", new { Code = "IDTYPE", addEmptyRow = false });
}).ServerFiltering(true);
}))
</td>
</tr>
</table>
</div>
</div>
</div>
Controller
public ActionResult PersonUpdate([DataSourceRequest] DataSourceRequest request,Guid id,string name,string surname,string[] IDTYPES) { ....
Here is sample header data that captured from chrome when press update button on on Pop-Up window.IDTYPES values are coming from combobox's selected item object.I need to pass some values of IDTYPE(eg.IDTYPES.CODE,IDTYPES.ID,IDTYPES.REFERENCEID ) to controller from view.
sort:
group:
filter:
CITIZENNO:-
ID:78ef069f-c31b-4828-81e8-4ede52ee0818
NAME:ABDULAZIZ
SURNAME:AL GARNI
IDTYPES.ID:69bd3ef7-fc80-4f26-a978-963ed670d3fe
IDTYPES.REFERENCEID:57ff1ea9-6cb4-4d7e-abc7-caa367fd4627
IDTYPES.CODE:3
IDTYPES.DESCRIPTION:PASSPORT ID
IDTYPES.PARENTID:00000000-0000-0000-0000-000000000000
IDTYPES.ISSELECTED:false
IDTYPES.COUNT:0
IDTYPES.ISACTIVE:false
IDTYPES.ISDEFAULT:false
IDTYPES[ID]:69bd3ef7-fc80-4f26-a978-963ed670d3fe
IDTYPES[REFERENCEID]:57ff1ea9-6cb4-4d7e-abc7-caa367fd4627
IDTYPES[CODE]:3
IDTYPES[DESCRIPTION]:PASSPORT ID
IDTYPES[PARENTID]:00000000-0000-0000-0000-000000000000
IDTYPES[ISSELECTED]:false
IDTYPES[COUNT]:0
IDTYPES[ISACTIVE]:false
IDTYPES[ISDEFAULT]:false
The value from the ComboBox can be retrieved as described in the documentation, using JQuery. After that, you can just post it to your controller using Ajax:
var selectedValue = $("#IDTYPES").data("kendoComboBox").text();
$.ajax({
url: "#Url.Action(actionName, controllerName)" + "/?id="+userid+"&name="+username+"&surname="+usersurname+"&idtype="+selectedValue,
success: function(){ /*handle success*/},
error: function(){ /*handle error*/}
});
You would also need to change your Controller Action definition as bellow. As far as I understand you don't need all the values of the ComboBox, but only the selected value:
public ActionResult PersonUpdate([DataSourceRequest] DataSourceRequest request,Guid id,string name,string surname,string IDTYPE)

Access form values in controller, i'm trying to post whole grid back to post method ASP.net MVC

I displayed a list of data in form of a grid [basic html table] and placed text boxes so that we can edit inside the grid and post the values so that I can save it. The list is not big , around 5-10 rows in it.
How to access these form values back in controller? FormCollection doesn't seem to work and I cannot even access the values through Request.Form[]. I want it back in a form of a list so that I can loop through it and get the new values.
.cshtml
<form action="/Parameter/StudentWeights" method="post">
<table>
<tr>
<th>
Category
</th>
<th>
CategoryAlias
</th>
<th>
YearCode
</th>
<th>
ClassKto8
</th>
<th>
Class9to12
</th>
<th></th>
</tr>
#foreach(var item in Model.StudentWeights) {
<tr>
<td>
#Html.HiddenFor(modelItem => item.CategoryId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category)
</td>
<td>
#Html.DisplayFor(modelItem => item.CategoryAlias)
</td>
<td>
#Html.DisplayFor(modelItem => item.YearCode)
</td>
<td>
#Html.EditorFor(modelItem => item.ClassKto8)
</td>
<td>
#Html.EditorFor(modelItem => item.Class9to12)
</td>
</tr>
}
</table>
<input type="submit" value = "Submit" />
</form>
controller
[HttpPost]
public ActionResult studentWeights(FormCollection collection)
{
try
{
// TODO: Add update logic here
//service.
foreach (var item in collection)
{
int x = item. // i want to loop through it and access the values.
}
}
catch
{
return View();
}
}
please help me how to get these values. I don't want to use JEditable or any third party jQuery tools.
Is there any way to create a custom type and assign values in JavaScript or jQuery upon button click and then send it to my controller action?
Thank you very much, any suggestion would be much helpful.
You need to access the form collection differently. The form collection is a key value pair of the values posted to the controller. formcollection["postvalue"]
[HttpPost]
public ActionResult studentWeights(FormCollection formCollection)
{
foreach (string _formData in formCollection)
{
var x = formCollection[_formData];
}
}
Here are several way to iterate through a form collection
http://stack247.wordpress.com/2011/03/20/iterate-through-system-web-mvc-formcollection/

Categories