passing model from view to controller using ajax call? - asp.net-mvc

I am making an application, in which it is required to create a lead when user enters the mobile number and tab out, the lead is created if entered mobile number is valid(with all other details on the form). But when i am passing model from view to controller the data i 'm getting null.
View
#{
ViewBag.Title = "EmailQuote";
Layout = "~/Views/Shared/Template.cshtml";
}
#model Max.VirtualSalesManager.UI.ViewModels.LeadViewModel
#{
var data = Html.Raw(Json.Encode(Model));
}
<script src="#Url.Content("~/Scripts/Common.js")" type="text/javascript"></script>
<h2>
EmailQuote</h2>
#using Acidaes.VirtualSalesManager.UI.Helpers
#using (Html.BeginForm("GenerateEQuote", "Quote", FormMethod.Post, new{id="frmEmailQuote" }))
{
#Html.MandatoryLabel("Name", false, new { style = "width: 50px; display: inline" }) #Html.FullName()
#Html.MandatoryLabel("City", false, new { style = "width: 50px; display: inline" }) #Html.DropDownListFor(m => m.CommunicationAddress.City, new SelectList(ViewBag.CityList, "Key", "Value"), "select", new { id = "ddlCity" })
#Html.MandatoryLabel("Mobile No.", false, new { style = "width: 100px; display: inline" }) #Html.TextBoxFor(m => m.MobileNumber, new { style = "width: 100px", id = "txtmobilenumber", onBlur = "createLead('"+#data+"')" })
#Html.MandatoryLabel("Email ID", false, new { style = "width: 80px; display: inline" }) #Html.TextBoxFor(m => m.EmailId, new { style = "width: 100px" })
#Html.HiddenFor(m => m.LeadId)
<input type="submit" id="btnSubmit" />
}
Js
function createLead(data) {
var number = /^[0-9]+$/;
var mobileNumber = document.getElementById('txtmobilenumber').value;
if (mobileNumber.match(number) && mobileNumber.length == 10) {
var jsondata = JSON.stringify(data);
var Parameters = "{'data':'" + ("#frmEmailQuote").serialize() + "'}";
Events.DoServerRequest('/MAXVSM/Quote/test', Parameters, GetLeadId);
}
}
DoServerRequest Function
DoServerRequest: function (url, data, funSuccess) {
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: funSuccess,
error: function () {
alert("Error in getting list");
}
});
Controller
[HttpPost]
[ActionName("test")]
public JsonResult test(LeadViewModel data)
{
LeadViewModel t = new LeadViewModel();
t.MobileNumber = data.MobileNumber;
return Json(t);
}
The data reaching fine from view to ajax function, but when the data is reaching to controller it is null.

Try removing contentType from your ajax call:
DoServerRequest: function (url, data, funSuccess) {
$.post({
type: "POST",
url: url,
data: data,
async: false,
dataType: "json",
success: funSuccess,
error: function () {
alert("Error in getting list");
}
});
}
The server is not expecting JSON content but application/x-www-form-urlencoded which is the default value.
This means you should also use a normal Javascript object or string as data:
if (mobileNumber.match(number) && mobileNumber.length == 10) {
Events.DoServerRequest('/MAXVSM/Quote/test', $("#frmEmailQuote").serialize(), GetLeadId);
}

Related

How Bind Model data to Telerik Controls?

I am using bellow code to insert the data to db. While Clicking the save button the data should be bind to the model and needs to be posted to controller action . But the data is not bind to the model. What is the issue in the bellow code . Any please help me to solve the below issue.
#(Html.Kendo().TextBoxFor(model => model.Code)
.HtmlAttributes(new { placeholder = "Enter Code", required = "required",
validationmessage="Code is Required" })
)
<input type="button" title="Save" id="btnsave" value="Save" onclick="submit()"/>
<script>
function submit(data) {
debugger;
console.log("Cosoledata "+JSON.stringify(data))
$.ajax({
type: "POST",
url: '#Url.Action("action", "controller")',
data: { data: #Model },
dataType: "json",
success: function (response) {
}
});
}
</script>
data: { data: #Model },
In the JavaScript script, you can directly get the Model data via the #Model.
To send the model data to the controller method, you could create a JavaScript object, then use JQuery to get the related property value (such as Code), then send the object to the controller method.
Please refer the following sample:
View page:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#btnCreate").click(function () {
var review = {}; //create a JavaScript Object.
//user JQuery to get the entered value, and set the property value.
review.ReviewID = $("#ReviewID").val();
review.MovieID = $("#MovieID").val();
review.goreRating = $("#goreRating").val();
review.shockRating = $("#shockRating").val();
review.jumpRating = $("#jumpRating").val();
review.plotRating = $("#plotRating").val();
review.supernaturalRating = $("#supernaturalRating").val();
review.starRating = $("#starRating").val();
//if you want to send multiple objects, you could create an array.
//var reviewlist = [];
//reviewlist.push(review);
$.ajax({
url: "/Home/AddReview",
method: "Post",
data: { "reviewViewModel": review } , // { "reviewViewModel": reviewlist },
success: function (response) {
alert(response);
},
error: function (response) {
console.log("error");
}
})
});
})
</script>
}
Controller method:
[HttpPost]
public IActionResult AddReview(ReviewViewModel reviewViewModel)
{
if (ModelState.IsValid)
{
//do something
}
return View();
}
The result as below:

C# razor select2 disable

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

jquery autocomplete with ASP.NET MVC

I am trying to get jQuery autocomplete in a textbox. But I don't seem to be able to display the data from my JsonResult in the view, I checked with firebug and verfied that the data is transferred from server, just doesn't disply in the TextBox. I don't get any errors.
Here's my code :
public JsonResult search(string term)
{
// string prefixText =SearchString;
var FamilyLastName = _repository.FamilySearch(term);
var data=FamilyLastName.ToList();
return Json(data);//.Select(x => new { label = x, ID = x }));
}
#using (Html.BeginForm())
{
<label for="SearchString">My Autocomplete:</label>
<input class="form-control" type="text" name="SearchString" id="SearchString" autocomplete="off" />
}
<script type="text/javascript">
$(document).ready(function () {
var param = { "searchstring": $("#SearchString").val() };
$("#SearchString").autocomplete({
autoFocus: true,
source: function (request, response) {
// call your Action
$.ajax({
url:'search?term=' + $("#SearchString").val(),
// data:"{'term':'" +$("#SearchString").val() + "'}",
dataType: 'json',
method: "post",
contentType: "application/json; charset=utf-8",
success: function (data) {
return{
label:data.FamilyLastName
};
},
select:
function (event, ui) {
$('#SearchString').val(ui.item.label);
return false;
},
});
},
minLength: 1,// requ

MVC 3 Webgrid with dropdownlist, get selected value on postback

I have a webgrid with dropdownlist and onchange it postback the page. I am trying to get the selected value of the dropdownlist.
Following is my Controller.
public ViewResult Index()
{
//var albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre);
var model = new AlbumActionModel { Actions = new[] { new SelectListItem { Text = "Accept", Value = "Accept" }, new SelectListItem { Text = "Deny", Value = "Deny" } }, Albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre) };
return View(model);
}
Following is my View.
<div>
#{
WebGrid grid = new WebGrid(Model.Albums, defaultSort: "Title", selectionFieldName: "SelectedRow");
}
#using (Html.BeginForm("Index", "Album", FormMethod.Post, new { id = "TheForm" }))
{
#grid.GetHtml(columns: grid.Columns(grid.Column("Edit",
format: #<text> #Html.ActionLink("Edit", "Edit", new { id = item.AlbumId })></text>),
grid.Column("AlbumId"),
grid.Column("Title"),
grid.Column("Action",
format:
#<span>
#{var index = item.AlbumId.ToString();}
#Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--", new { onchange = "this.form.submit();" })
</span>),
grid.Column("Delete",
format: #<text> #Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })></text>)))
</div>
Thanks in advance.
In your dropdownlist try the following statement:
#Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--",new { #onchange = "Submit(this.value);" })
Now write a function in your <script> tag to post it to the page
<script type="text/javascript">
function Submit(e)
{
//write it to post to the controller using ajax
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("Submit", "ControllerName")',
data: ({ value: e}),
success: function (result) {
//do something
}
,
error: function (result) {
//do something
}
});
}
</script>
Hope this helps.

ASP.NET MVC 3 + jQuery Ajax JSON - Prevent JSON from opening in new page

I have an Action Method that returns a JSON-serialized object. The problem I'm having is that the JSON returned is opening in a new page, instead of being processed by the "success" function of the jquery.Ajax method.
Here's the controller action:
[HttpPost]
public ActionResult AddAssignment(AssignmentViewModel avm)
{
db.Assignments.Add(new Assignment
{
Name = avm.Name,
DueDate = DateTime.Parse(avm.DueDate),
CourseID = avm.CourseID,
IsComplete = false
});
db.SaveChanges();
avm.Course = db.Courses
.Where(x => x.CourseID == avm.CourseID)
.SingleOrDefault()
.Name;
return Json(avm);
}
Here's the View (form):
#model Fooburg.Mvc.Models.AssignmentViewModel
<h2 style="margin: 0 0 24px 0">Add Assignment:</h2>
#using (Html.BeginForm("AddAssignment",
"Assignments",
FormMethod.Post,
new { #id = "add-assignment-form" }))
{
<dl class="tabular">
<dt>Course:</dt>
<dd>
#Html.DropDownListFor(x => x.CourseID, new SelectList(ViewBag.Courses, "CourseID", "Name"))
</dd>
<dt>Assignment:</dt>
<dd>
#Html.TextBoxFor(x => x.Name)
</dd>
<dt>Due Date:</dt>
<dd>
#Html.TextBoxFor(x => x.DueDate, new { #class = "date" })
<script type="text/javascript">
$(function () {
$('.date').datepicker({ dateFormat: "mm/dd/yy" });
});
</script>
</dd>
</dl>
<p>
<input type="submit" value="Add Assignment" id="new-assignment-submit" />
</p>
}
And here's the javascript:
$(function () {
$('#add-assignment-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
});
});
I have tried the event.stopPropogation() method, but didn't change my problem
EDIT: I've updated my javascript to the following, but I'm still getting the same result
$('#add-assignment-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
You need to return false; or event.preventDefault() to prevent the browser from submitting the form normally.
You have two options here,
Use Ajax.BeginForm() instead of Html.BeginForm() that you would use like
#using(Ajax.BeginForm( "AddAssignment", "Assignments",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "output"})) {
...
}
and get rid of the javascript code.
Or call event.prevendDefault() in
$('#add-assignment-form').submit(function (event) {
// ...
event.preventDefault();
});
Just specify
return false;
after your $.ajax() call
UPDATE
$(function () {
$('#add-assignment-form input[type=submit]').click(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
});
Have you checked if there are other javascript errors on the page that might be causing this unexpected behaviour? I would suggest Firebug for FF or Javascript Console for Chrome.
Also, I've noticed that sometime FF has issues if you don't specify the script type, so make sure your type is set to "text/javascript".
hth,
-covo

Resources