MVC 3 Pass multiple ints / collection via ajax to controller - asp.net-mvc

On my form I have several hidden fields with the same name (RemoveId)
<input type="hidden" value="1" name="RemoveId" />
<input type="hidden" value="2" name="RemoveId" />
<input type="hidden" value="3" name="RemoveId" />
<input type="hidden" value="4" name="RemoveId" />
<input type="hidden" value="5" name="RemoveId" />
I would like to pass checked items (int(s)) to a controller via ajax/json
How would i do it?
thanks

here is something that should help
Using getElementsByName on the name "RemoveId" will give you an array
var list = document.getElementsByName("RemoveId");
var arrId = [];
for (var i = 0; i < list.length; i++) {
arrId.push(list[i].value);
}
Pass this list of id's prepared to the controller
$(function(){
$.ajax({
type: "POST",
url: "#Url.Action("PostArray")" %>",
data: {idArray: arrId},
dataType: "json",
success: function(msg){console.log(msg)}
});
})
and here is how your controller should look like
[HttpPost]
public ActionResult PostArray(int[] idArray)
{
// do your thing..
}

Try to do this:
<input type="hidden" value="1" name="RemoveId" />
<input type="hidden" value="2" name="RemoveId" />
<input type="hidden" value="3" name="RemoveId" />
<input type="hidden" value="4" name="RemoveId" />
<input type="hidden" value="5" name="RemoveId" />
<input type="button" value="do" class="send" />
<script type="text/javascript" >
$(function () {
$(".send").click(function () {
var myValues = [];
$("[name = 'RemoveId']").each(function (index, element) {
myValues.push($(element).val());
});
$.ajax({
type: "POST",
url: "/Home/Method",
data: { myValues: myValues }
});
});
})
</script>
[HttpPost]
public ActionResult Method()
{
var b = Request["myValues[]"].Split(',').ToList();
return null;
}

Related

how to write onclick event in reactjs?

here is my code
this is simple form. I am trying to call on click event on button click
render: function () {
return (
<form className="commentForm">
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
You forgot to pass the onSubmit event for form
render: function () {
return (
<form className="commentForm" onSubmit={this.submit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
submit: function() {
// do your stuff
}
try this:
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
Can you try like this
handleTextChange(e) {
const { name, value } = e.target;
this.setState({
[name]: value
});
}
_handleSubmit(e) {
e.preventDefault();
let { author, text} = this.state;
// dispatch the submit function
}
render: function () {
return (
<form className="commentForm" onSubmit={this._handleSubmit}>
<input
type="text"
placeholder="Your name"
name="author"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
name="text"
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
u want onclick method here it is onsubmit same work of onclick.
handleSubmit(){
console.log(this.state.author);// u can see the value of autor and say somthing input vale in here it is coming right value or not
console.log(this.state.text);
axios.post(route,{
name:this.state.author, //these name and say are the variable whice are use to take the values to back end
Say :this.state.text
}).then({response}); //here u cn give some thing to disply after data add to database.
}
<form className="commentForm" onsubmit={this.handleSubmit.bind(this)}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Submit" />
</form>
You need not have separate onChange for two fields unless you do something different in each of them.
Render:
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
name="author"
onChange={this.handleChange}
/>
<input
type="text"
placeholder="Say something..."
name="text"
onChange={this.handleChange}
/>
<button type="submit" >submit</button>
</form>
When submit is clicked :
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.author) //whatever you want to process the data with...
}
You can have single handleChange to set the state
handleChange = (e) => {
const { value, name } = e.target;
this.setState({ [name]: e.target.value })
}

jquery autocomplete with multiple sources

I have a web form with radio buttons and a input field for autocomplete. Based on the selected radio button a different webservice (url) needs to be called to work with the data that the user is entering in input field.
The following code works well, but I don't know how to make it more flexible to accept different URL's.
$("#txtCriteria").autocomplete({
source: function (request, response) {
$.ajax({
async: false,
delay: 500,
url: "../../CommonWebServices/wsEntity.asmx/ReportBuildings",
data: "{ 'Name': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.Text,
value: item.Value
} // end of return
})) // end of response
} // end of success
}); // end of ajax
}, // end of source
minLength: 1,
});
Here are the radio buttons. So If I select Region the webservice URL is different then the Building.
<input id="Radio1" type="radio" value="S" name="rblRptChoice" class="label" checked="checked" />State Wide<br />
<input id="Radio2" type="radio" value="P" name="rblRptChoice" class="label" />Prosperity Region<br />
<input id="Radio3" type="radio" value="R" name="rblRptChoice" class="label" />Region<br />
<input id="Radio4" type="radio" value="T" name="rblRptChoice" class="label" />Cluster<br />
<input id="Radio5" type="radio" value="C" name="rblRptChoice" class="label" />CEPD<br />
<input id="Radio6" type="radio" value="F" name="rblRptChoice" class="label" />Fiscal Agency<br />
<input id="Radio7" type="radio" value="B" name="rblRptChoice" class="label" />Building<br />
<input id="Radio8" type="radio" value="P" name="rblRptChoice" class="label" />CIP Code<br />
<input id="Radio9" type="radio" value="Y" name="rblRptChoice" class="label" />Year<br /><br />
<asp:Label ID="lblDetails" runat="server" Text="Enter Details"></asp:Label><br />
<input id="txtCriteria" type="text" placeholder="Enter Criteria" style="width:250px" />
Any assistance is appreciated.
I put the path value in a variable when the radio button is selected and then set the url to the variable.

Set radio button checked item from ASP MVC 3 controller

Below is a group of radio buttons that appear on my view. I am able to retrieve the selected item via this simple code
string criteria = filter["criteria"];
however I do not know how to retain the selected item. Once the controller posts back to the view the default radio button is always selected.
<form method="post">
#Html.TextBox("searchValue", ViewBag.CurrentFilter as string, new { placeholder = "Search" })
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" style="padding-top: 0px;" />
<span class="error" style="clear: both;">
#ViewBag.ErrorMessage
</span>
<br />
<br />
<input type="radio" name="criteria" id="bankName" value="bankName" checked="true"/>
<label for="bankName">Bank Name</label>
<input type="radio" name="criteria" id="EPURL" value="EPURL" />
<label for="EPURL">EPURL</label>
<input type="radio" name="criteria" id="specialNotes" value="specialNotes" />
<label for="SpecialNotes">Special Notes</label>
<input type="radio" name="criteria" id="email" value="email" />
<label for="email">Email</label>
<input type="radio" name="criteria" id="dynamicsId" value="dynamicsId" />
<label for="dynamicsId">Dynamics ID</label>
<input type="radio" name="criteria" id="stat" value="stat" />
<label for="fixed">Agent ID </label>
</form>
The answer to this question wound up being incredibly simple. First mistake I made was not using the #Html controls. Second was using FormCollection as an input parameter for the index controller. By changing the radio buttons to the following:
#Html.RadioButton("criteria", "bankName", true)<span>Bank Name</span>
#Html.RadioButton("criteria", "EPURL")<span>EPURL</span>
#Html.RadioButton("criteria", "specialNotes")<span>Special Notes</span>
#Html.RadioButton("criteria", "email")<span>Email</span>
#Html.RadioButton("criteria", "dynamicsId")<span>Dynamics ID</span>
#Html.RadioButton("criteria", "stat")<span>Agent ID</span>
and the signature of the Index method in the controller to this:
public ActionResult Index(string criteria, string searchValue)
The selected radio button stayed selected after the post back.
If I understand your need correctly you could set the name of the item you want checked in the ViewBag (or ViewData or Model) and set the checked property in your view accordingly. Something like this:
<form method="post">
#Html.TextBox("searchValue", ViewBag.CurrentFilter as string, new { placeholder = "Search" })
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" style="padding-top: 0px;" />
<span class="error" style="clear: both;">
#ViewBag.ErrorMessage
</span>
<br />
<br />
#{
var checkedItemName = ViewBag.CheckedItemName;
}
<input type="radio" name="criteria" id="bankName" value="bankName" checked="#((checkedItemName == "bankName"))"/>
<label for="bankName">Bank Name</label>
<input type="radio" name="criteria" id="EPURL" value="EPURL" checked="#((checkedItemName == "EPURL"))"/>
<label for="EPURL">EPURL</label>
<input type="radio" name="criteria" id="specialNotes" value="specialNotes" checked="#((checkedItemName == "specialNotes"))"/>
<label for="SpecialNotes">Special Notes</label>
<input type="radio" name="criteria" id="email" value="email" checked="#((checkedItemName == "email"))"/>
<label for="email">Email</label>
<input type="radio" name="criteria" id="dynamicsId" value="dynamicsId" checked="#((checkedItemName == "dynamicsId"))"/>
<label for="dynamicsId">Dynamics ID</label>
<input type="radio" name="criteria" id="stat" value="stat" checked="#((checkedItemName == "stat"))"/>
<label for="fixed">Agent ID </label>
</form>
Don't refresh the complete page...Use JQuery and do an Ajax call
$.ajax({
url: "Your Url",
async: true,
type: 'POST',
data: JSON.stringify({ ParameterName: Param_Value }),
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
//Success Callback
//Code to set value to your control
}
});

Hide/Disable submit button from controller

How can I hide a webform button from controller action? or Do I do it in webform itself?
There is a condition to hide/disable the button:
if (StudentType != "Senior")
{
Hide Button
}
Display Button
View:
<form method="post" action="/Student/Dispatch/">
<label for="id">Student Number: </label>
<input type="text" name="id" value="" /> <br /><br />
<input type="submit" value="Get Student(xls)" name="xls" /> &nbsp
<input type="submit" value="Get Student(pdf)" name="pdf" />
</form>
Controller:
[HttpPost]
public ActionResult Dispatch(string pdf, string id) {
if (!string.IsNullOrEmpty(pdf)) {
// GetPdf submit button was clicked
return StudentPdf(id);
}
// GetXls submit button was clicked
return StudentExcel(id);
}
You can use ViewData dictionary .
Controller:
if (StudentType != "Senior")
{
ViewData["isHideButton"] =true;
}
View:
<form method="post" action="/Student/Dispatch/">
<label for="id">Student Number: </label>
<input type="text" name="id" value="" /> <br /><br />
<% bool hideButton= false;
bool.TryParse(ViewData["isHideButton"],hideButton)%>
<%if(!hideButton)
{%>
<input type="submit" value="Get Student(xls)" name="xls" />
<%}%>
&nbsp <input type="submit" value="Get Student(pdf)" name="pdf" />
</form>

how to get an collection of ids int[] in post action (selected checkboxes)

I need to get in an action method the values from the selected checkboxes on a form
how would you do that ? (or probably get them all and see who was selected)
public ActionResult (int[] ids)
...
<input type="checkbox" value = "1" />
<input type="checkbox" value = "2" />
<input type="checkbox" value = "3" />
<input type="checkbox" value = "4" />
<%=Html.Submit(); %>
You could try giving the checkboxes a name (ids):
<input type="checkbox" name="ids" value="1" />
<input type="checkbox" name="ids" value="2" />
<input type="checkbox" name="ids" value="3" />
<input type="checkbox" name="ids" value="4" />
Should work with:
public ActionResult Index(int[] ids) { ... }

Resources