Get data-id value of textbox on form submit - c#

I have a textbox set-up, like so:
#Html.TextBoxFor(m => m.NewVehCode, new {data_id = "" })
When a user selects a vehicle, the description of the vehicle becomes the value of the textbox and the vehicle code (which is what I want to send to DB) becomes the data-id (not full code but I set the values like this):
$("#NewVehCode").val(vehDescription);
$("#NewVehCode").attr("data-id", vehCode);
This all works fine, except for the fact that when I submit, MVC grabs the value of the textbox.
Is there a way I can on submit, get the data-id of that textbox instead of the value?
Note that I'm not using .js to gather the data. Form calls a controller action that sends the model directly to the controller.

There is no way to submit values of "data" properties. I am not sure why you wanted to use data property (is that a requirement or not, not sure). But you can have a hidden property in the form so, when user selects a vehicle, along with data property of text box , update this hidden value. This hidden value will be submitted back to form.

Stephen Muecke's comment helped me trigger this solution:
I've added a hidden textbox to use for the vehicle code, and made the textbox that shows the description a standard textbox with no data binding.
<input id="newVehInput" readonly="readonly" class="longInput" type="text">
#Html.TextBoxFor(m => m.NewVehCode, new { style = "display: none"})
This way I can use the value with no issues:
$("#newVehInput").val(vehDescription);
$("#NewVehCode").val(vehCode);
(Will mark as answer in 2 days)

Add a hidden textbox to your html which you post back on submit
In your model:
public string Id {get;set;}
Render it in the view with a hidden class
And with js.
$("#vehicleList").on("change",function(){
$("#Id").val($vehCode)
})
When you submit the value of id should be set in your model

You can have a hidden field hold the Updated value.
HTML:
<input type="hidden" id="HiddenVehCode" name="HiddenVehCode" Value="0"/>
JS
$("#HiddenVehCode").val(vehDescription);
Note: you should have the model set up so that HiddenVehCode will reach the actionMethod on Form Submit.Something Like,
public int HiddenVehCode {get;set;}

Related

How to resolve hidden form field auto generated from #Html.CheckBoxFor

Whenever i create a boolean property in my ASP.NET MVC model and try to create a checkbox using #Html.CheckBoxFor i get a hidden form field autogenerated. I know it is happening for a good reason but whenever i submit my form and get that value using form collection it returns 2 values when it is in checked state. It submits value like this - 'true,false'. Now when i get the values using form collection and do bool.Parse() it throws an error because it cannot parse 'true,false' together. Is there any way around to get rid of hidden form field or should i try something while processing the request ??
In Model
[Display(Name ="Is Enabled")]
public bool IsEnabled { get; set; }
In Controller
public ActionResult Request(FormCollection collection)
{
bool valueIsEnabled=bool.Parse(collection["IsEnabled"])
}
In View
#Html.CheckBoxFor(m => m.IsEnabled, new {
#class = "custom-input"
})
When I click Checked
Expected Result - true
Actual Result - true,false
When I don't click checked
Expected Result - false
Actual Result - false
Ok I did some research and found that the CheckBox helper generates an additional hidden field with the same name as the checkbox (you can see it by browsing the generated source code):
<input checked="checked" id="Visible" name="Visible" type="checkbox" value="true" />
<input name="Visible" type="hidden" value="false" />
So both values are sent to the controller action when you submit the form. Here's a comment directly from the ASP.NET MVC source code explaining the reasoning behind this additional hidden field:
if (inputType == InputType.CheckBox) {
// Render an additional <input type="hidden".../> for checkboxes. This
// addresses scenarios where unchecked checkboxes are not sent in the request.
// Sending a hidden input makes it possible to know that the checkbox was present
// on the page when the request was submitted.
...

BeginForm() take complex input value into routing

I have a little problem with binding <input> value into routing of the beginForm GET action when submitting.
Firstly, the relevant code :
[Route("Company/{companyID:int}/MarketOffers/{PagingParam.PageNumber=1}")]
public ActionResult MarketOffers(int companyID, PagingParam pagingParam)
* This is declaration of action that I am dealing with. PagingParam have property PageNumber of int type.
#using (Html.BeginForm(RouteDataHelper.ActionName, RouteDataHelper.ControllerName, FormMethod.Get, new { companyID = Model.Info.CompanyID }))
* In the BeginForm I am only using companyID because PageNumber will vary depending on what the user clicks on the website and because of that it's not supplied here.
<input id="PagingParam.PageNumber" name="PagingParam.PageNumber" type="hidden" value="1">
* This is input which value should be appended to URL. It's inside the form which generation code you see above. The value changes by javascript just before submitting the form.
When I input link like :
http://localhost:38120/Company/2037/MarketOffers/3
* Everything is ok. PagingParam.PageNumber sets its value to 3. This is desired behaviour.
But when I submit the form with PagingParam.PageNumber input field then my URL looks like :
http://localhost:38120/Company/2037/MarketOffers?PagingParam.PageNumber=2
Instead of
http://localhost:38120/Company/2037/MarketOffers/2
I exactly know that I could deal with that and change form action value using javascript+JQuery but I have a feeling that there is a way to do this automatically in MVC without writing JavaScript.
So the question is : Can I do something to automatically generate desired link when I am passing form which action is (for example) "/Company/2037/MarketOffers" and append PagingParam.PageNumber to generated URL without writing JavaScript?
All inputs inside a form that make a GET have their values added as query string parameters because a browser has no knowledge of the routes on your server.
Its not possible to generate ../Company/2037/MarketOffers/3 without using javascript to modify the action attribute of the form

MVC get a form control data- attribute value in a post ActionResult

i'm trying to recreate something i did back in winforms days with html data- attributes in mvc.
you could set an attribute on a form control using this:
txtTest.Attributes.Add("data-myattribute", "my value");
and then read it back once the form had been posted using:
txtTest.Attributes["data-myattribute"]
adding the attributes in mvc is a breeze:
#Html.TextBoxFor(m => m.FirstName, new { data_myattribute = "my value" })
just can't figure out how to read them in the action result once the form has been posted?!
been searching around and whilst i can find loadsa posts on how to set data- attribute values and read them in javascript, i can't find anything that'll tell me how to get them back in the code...
anyone out there know the magic answer?!
Data attributes are not included in the data that's posted with the form, so there is no way to read them in your controller action. Try using a hidden field instead:
<input type="hidden" name="FirstNameAttribute" value="my value" />
This'll bind back to a model property:
public string FirstNameAttribute { get; set; }

Get value of another form in Controller

I have two forms on the page. One of them, say MainForm, is using #using (Html.BeginForm... to call an action upon submit, and the other, RadioForm, just consists of a bunch of radios with no submit button (it's used to trigger the display of MainForm). If an error occurs during server-side validation, I return the View from the Controller. This though causes the radio to be deselected.
What I'm thinking is to grab the selected value of RadioForm so that I can set it again after the return. How would I do this? Is there a better way of persisting the state of the RadioForm?
The browser won't post any form values outside of the form that's submitted, so there's no way to do this server-side. One solution would be to maintain a hidden field and update this with jQuery within the main form:
#Html.HiddenFor(m => m.RadioValue, new { #class = "radio-tracker" })
Give each of your radio buttons a class of, say, "radio-hidden" and use the following:
$('.radio-hidden').click(function() {
$('.radio-tracker').val($(this).val());
});
You can then create a property on your main form's model called RadioValue and it will be bound to the selected radio button's value on post.
Then, when you return your view again, you can use this value to pre-populate the radio buttons.
Alternatively, you could look at using AJAX.
Instead of having the radios on a different form you need to have them on the one that submits. This way you can pass those values back to the view.
You can use the Ajax.BeginForm method instead of Html.BeginForm which allows you to specify the update target. This will allow you to update the submitted form only and not affect the radio form.
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.beginform(v=vs.108).aspx

updating textbox value

I have an input tag having some text in it. Now I would like that onclick of a button the text will be changed.
For some reason it is not being changed.
This is the input tag:
<input id="network_table" type="text" value="oldValue" runat="server"/>
the following is the way I am trying to change the value of the input tag:
network_table.Value = "newValue";
network_table.Text = "newValue";
Bind the "onclick" event and apply this these methods:
In jQuery :
$('#network_table').val("your val");
http://docs.jquery.com/Val
Javascript
document.getElementById('network_table').value = "your val";
you can do it serverside with "OnClick" event on button, assuming your controls are defined with runat="server" attribute
http://msdn.microsoft.com/fr-fr/library/system.web.ui.webcontrols.button.onclick(v=VS.80).aspx
You could try and assign some meaningless class to the input and use that as a reference point to get in hold of the input field.
<input id="network_table" type="text" value="oldValue" runat="server" class="myInputField"/>
$('.myInputField').val('newValue');
Using the id will not work because you are using the 'runat=server' and it makes the id unavailable on client side and you would need to get the unique id first to be able to get in hold of it. This is a lot cleaner way but you need to make sure not to use the class elsewhere to avoid ambiguous results.
Here is a jsfiddle example which does what you want but on load.
http://jsfiddle.net/yX5ze/

Categories

Resources