Pass FormCollection to controller with ajax - ajax

How can I pass form collection to controller with jquery or ajax on change for drop down list?
Can I call an action in my controller and give it my form if I don't use submit button?
#using (Html.BeginForm("Create","Order", FormMethod.Post, new {#class = "form-horizontal", #name="forma"})) {
#Html.ValidationSummary(true)
#Html.Partial("_CreateOrEdit", Model)
<div class="form-actions no-margin-bottom">
<input type="submit" value=#Html.LocalizeString("String_Save") class="btn btn-primary" >
#Html.LocalizeString("String_BackToList")
</div>
}
and part of that partial is (it has many more fields but I think they don't matter for question)
<div class="control-group">
<div class="control-label">
#Html.LocalizedLabelFor(model => model.BuyerId)
</div>
<div class="controls">
#Html.DropDownListFor(model => model.BuyerId, ((IEnumerable<SalesAgent.Core.Entities.Buyer>)ViewBag.PossibleBuyers).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Name),
Value = option.Id.ToString(),
Selected = (Model != null) && (option.Id == Model.BuyerId)
}), #Html.LocalizeString("String_Choose"),new {#class="searchable" })
#Html.ValidationMessageFor(model => model.BuyerId)
when I change dropdown list I want to call an action from my controller and pass it my current form data. How do I do that?

var input = $(':input');
$.ajax({
type: "POST",
data: input,
url: "URL",
success: function (items) {
//TODO
}
});
In controller I recive it to a FormCollection and then I can do what I need with form data.

I think like this...
$("#BuyerId").change(function() {
var model = {
// name of model member : value of model member
// BuyerId : $("#BuyerId").val(),
// ....your form data :)))
}
$.ajax({
url : //your method of controller url,
type: "POST",
data: {model : model} // name of model object what send to your controller
});
});

Related

How to get input data from MVC ViewModel into ajax post

I am fetching data from a SQL database table into an ASP.NET MVC Razor view but I have troubles getting changed input data into an Ajax post such as:
#model MyViewModel
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
var postData = #Html.Raw(Json.Encode(#Model));
//alert(postData.Test);
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}
When I load the view everything is displayed correctly. The controller action is triggered correctly and the Id (which can not be altered) is passed properly too. However when input fields are changed not the changed values get passed to the controller but the original values that were fetched into the view.
The serialization seems to work, since the alert (postData.Test) returns a value - but always the unchanged one.
Any help would be appreciated.
var postData = #Html.Raw(Json.Encode(#Model));
This line is the culprit. When Razor renders the script, it will assign the original/unchanged model to your postData variable.
If you use "Inspect Element" or dev tools to check the value of postData, you'll see that the values won't change because they're statically assigned.
You need to check for the new values every time you click the button by using
var postData = $("form").serialize();
And be sure to wrap your input fields inside a form tag. See code below:
<form>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
</form>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
// use form.serialize or use the id/class of your form
var postData = $("form").serialize();
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}

MVC Controller receiving null values from ajax

I'm trying to send an Ajax post to mvc controller contains two parameters.
First parameter: serialized model (Folder)
Second parameter: Array (Periods)
The problem is the controller received null values in the first parameter:
Javascript code :
var data = JSON.stringify({
Folder: $('#Folder').serialize(),
Periods: periodsArr
});
function save(data) {
return $.ajax({
type: 'POST',
//cache: false,
contentType: 'application/json', //Without folder not empty and period is empty
//traditional: true,
//dataType: "json",
url: '#Url.Action("AddOrEditFolder", "Folder")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!" + Error);
}
});
}
Html code:
<div class="card-body">
#using (Html.BeginForm(null, null, new { #id = string.Empty }, FormMethod.Post, new { #id = "Folder" }))
{
#Html.HiddenFor(model => model.FolderID)
<div class="row">
<label for="FirstNameAR" class="col-sm-2 control-label">الإسم الشخصي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameAR, new { htmlAttributes = new { #id= "FirstNameAr", #class = "form-control" } })
</div>
<label for="FirstNameFR" class="col-sm-2 control-label">الإسم العائلي</label>
<div class="col-sm-4">
#Html.EditorFor(model => model.Trainee.FirstNameFR, new { htmlAttributes = new { #id = "FirstNameFr", #class = "form-control" } })
</div>
</div> <br />
Controller code:
[HttpPost]
//[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrEditFolder(Folder Folder, Period[] Periods)
{
//Folder Folder = JsonConvert.DeserializeObject<Folder>(Obj);
using (InternshipsEntities dbContext = new InternshipsEntities())
{
//Some code here
}
}
How can I solve that problem ?
Use below code to create data object to pass in Ajax request.
var Folder = { };
$.each($('#Folder').serializeArray(), function() {
Folder[this.name] = this.value;
});
var data = {
Folder: Folder
Periods: periodsArr
};

How to pass data from View in Asp.NET MVC

i want to get the value of textbox for Controller
I used Ajax.ActionLink("Search","Result",new{id="**VALUE**"}, new AjaxOptions{...})
#* This is the Index.cshtml *#
<input id="cityName" type="text" class="form-control" placeholder="Enter a CityName">
#Ajax.ActionLink("Search", "Result", new { id = "I want to get the cityName" }, new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "cityInfo", LoadingElementId = "loading" }, new { #class = "btn btn-default" })
<div id="cityInfo"> #When I click the actionlink , the controller will return a partialview
#Html.Partial("Result", Model)
</div>
#*This is the Result.cshtml*#
<p>
#if (#Model!=null)
{
#Model.cityInfo
}
</p>
this is the index.cshtml ->>
enter image description here
Thanks
public PartialViewResult Result(string cityName)//this is the controller
{
CityModel city = new CityModel(cityName);
city.getInfo();
return PartialView("Index",city);
}
You can write a function like below:
Ajax.ActionLink("Search","Result",new{id="id"}, new AjaxOptions{...}) //set temp value
$(document).ready(function(){
//init value
var value = $('#cityName').val();
var href = $('a').attr('href').replace('id', value);
$('a').attr('href', href);
});

How to submit entire form to MVC Controller Action using DataTables Ajax

I'm revisiting a problem I had early on with a page that contains quite a few input and select controls in a form. I prefer that my Controller Action uses the View Model to determine the input values, but the model's members are always empty when submitted. Here is my undesirable WORKING code, briefly:
VIEW MODEL:
public class MyViewModel
{
[Display(Name = "Project Name")]
public string ProjectName { get; set; }
[Display(Name = "Project Country")]
public string ProjectCountry { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
RAZOR VIEW:
#model My_Web_App.Models.MyViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myform" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProjectName)
<div class="col-md-9">
#Html.EditorFor(model => model.ProjectName)
</div>
</div>
<!-- Project Country -->
<div class="form-group">
#Html.LabelFor(model => model.ProjectCountry)
<div class="col-md-4">
#Html.DropDownListFor(
x => x.ProjectCountry,
new SelectList(Model.Countries, "Value", "Text"))
</div>
</div>
<table id="mytable">
<thead>
<tr>
<th>Data1</th>
<th>Data2</th>
<th>Data3</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id="btnSubmit" type="submit">Submit</button>
}
<script type="text/javascript">
$('#btnSubmit').click(function (event) {
event.preventDefault();
oTable = $('#mytable').dataTable({
"ajax": {
"url": "/MyController/MyJsonResult/",
"type": "POST",
"data": {
ProjectName: $('#ProjectName').val(),
ProjectCountry: $('#ProjectCountry').val()
}
}
});
return false;
});
</script>
CONTROLLER:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyJsonResult()
{
string projectName = Request["ProjectName"];
string projectCountry = Request["ProjectCountry"];
... DO SOMETHING ...
return Json(new { data = dosomethingresult }, JsonRequestBehavior.AllowGet);
}
The above code works in that I can get the View's form variables and use them to determine the results to return. Obviously I've left out a lot of code, a lot of form variables, and a lot of controller logic. I don't want to convert strings to integers, worry about whether a POST var is empty or null, etc. There are so many form variables I would like MVC to take care of this for me. For example:
PREFERRED CONTROLLER ACTION:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyJsonResult(MyViewModel model)
{
string projectName = model.ProjectName;
string projectCountry = model.ProjectCountry;
... DO SOMETHING ...
return Json(new { data = dosomethingresult }, JsonRequestBehavior.AllowGet);
}
The problem with the preferred controller action above is that the contents of model are always null when using DataTables Ajax.
model is initialized with valid data if I make the Ajax call outside of the DataTables initialization. :
$('#btnSubmit').click(function (event) {
event.preventDefault();
$.ajax({
url: "/MyController/MyJsonResult/",
type: "POST",
dataType: "json",
data: $('#myform').serialize()
});
return false;
}
The data setting just above correctly serializes all of the form fields and MVC successfully creates the View Model object for me to use in the Controller Action. Unfortunately, "data": $('#myform').serialize() in the DataTables Ajax does not work. The model is uninitialized (nulls and zeros) when the Controller Action is called.
How can I pass my entire form to the Controller Action using DataTables Ajax so that my View Model object contains correct data from the View's form?
I have been searching for a solution for a long time. Way too long. :S
Try this in your Razor view:
#using (Html.BeginForm("MyJsonResult", "MyController", FormMethod.Post, new { id = "myform" }))

Using Jquery to collect data, use data to get a Partial View from the controller, and append the passed information to the end of a page

I am attempting to append a partial view to the end of my 'currently displayed page' when a selection from a dropdown menu is chosen.
This is the dropdown from my view:
<div>
#Html.DropDownListFor(x => x.DropDownInfo, Model.Info, "DefaultSelection")
#Html.ValidationMessageFor(model => model.Courses)
</div>
I am in most need here in my Jquery. What do I need to do to append the PartialView that is returned by my controller (pasted below)? My current Jquery:
$(document).ready(function() {
$("#DropDownInfo").change(function() {
var strSelected = "";
$("#DropDownInfo option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Controller/PreFillMethod/?MethodString=" + strSelected;
$.post(url, function(data) {
//*****
// Assuming everything else is correct,
// what do I do here to have my partial view returned
// at the end of the currently displayed page?
//*****
});
});
});
This is the part of my controller that replies with a PartialView (I want the string from the dropdown selection to be passed into this controller to ultimately be used to fill in a field in the PartialView's form) :
public PartialViewResult PreFillCourse(string selectedFromDropDown)
{
ViewBag.selectedString = selectedFromDropDown;
MyViewModel preFill = new MyViewModel
{
Title = selectedFromDropDown, // I am using this to pre-fill a field in a form
};
return PartialView("_PartialViewForm", preFill);
}
The Partial View (in the case that it matters):
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>CourseTemplates</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
I am open to suggestions if I am approaching the situation entirely incorrectly.
My goal is to have a user select a 'template' from the drop-down menu and have that template's data autopopulate into a form below the drop-down.
My Jquery is very rough - I am using this post as a guide
you should have a div in your view
<div id ="divToAppend">
</div>
then append the partial view to your div
$(document).ready(function() {
$("#DropDownInfo").change(function() {
var strSelected = "";
$("#DropDownInfo option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Controller/PreFillMethod/?MethodString=" + strSelected;
$.post(url, function(data) {
$('#divToAppend').html(data);
//*****
// Assuming everything else is correct,
// what do I do here to have my partial view returned
// at the end of the currently displayed page?
//*****
});
});
});

Resources