Can't serialize Telerik MVC controls in Ajax call - asp.net-mvc

I am having problems passing my model from my view via an Ajax call to my controller. All of the model properties that have Telerik html 'For' controls do not persist in the model. The only way I can access those values in the controller is using Request["control_name"]. All other standard controls like input type=text serialize just fine. What am I doing wrong?
Here is my ajax call:
function ImportLogFile() {
$.ajax({
url: '/Job/ImportLogFile',
type: 'POST',
data: $("form").serialize(),
success: function (data)
{
$('body').css('cursor', 'auto');
alert("Word Counts imported.");
},
error: function (xhr, status, error)
{
alert(status + ": " + strip(xhr.responseText).substring(0, 1000) + "...");
}
});
}
Controller:
[HttpPost]
public ActionResult ImportLogFile(tblJobTask model)
{
...
}
View:
#model viaLanguage.Jams.Data.tblJobTask
<html>
<head></head>
<body>
#using (Html.BeginForm())
{
<label class="editorLabel">CAT Tool Type:</label>
#{ Html.Telerik().ComboBoxFor(model => model.CatToolID)
.Name("JobTask_CatToolID")
.BindTo(new SelectList((IEnumerable)ViewData["CatTools"], "CatToolID", "Description"))
.HtmlAttributes(new { style = "width:220px;" });
}
<input id="btnImport" type="button" onclick="ImportLogFile();" />
}
</body>
</html>

i believe .Name("JobTask_CatToolID") is the source of problem. when you change Name attribute of combobox to something other than property name it will not automatically bound to the property by modelbinder. ModelBinder just looks at posted keys and then searches for matching properties in model and populates them accordingly. and when binder finds the key JobTask_CatToolID it probably finds no matching property in the model and hence it is not assigned to any property. you can check this by omitting the Name(---) method and then posting data to your controller.

Related

Can you just update a partial view instead of full page post?

Is there a way to submit a partial view form in asp.net mvc without reloading the parent page, but reloading the partial view only to its new state? Similar to how knockout.js updates using data-bind.
My data table renders with a variable number of columns/names so I don't think knockout.js is an option for this one, so I am trying to use a partial view instead.
Not without jQuery.
What you would have to do is put your Partial in a div, something like:
<div id="partial">
#Html.Partial("YourPartial")
</div>
Then, to update (for example clicking a button with the id button), you could do:
$("#button").click(function () {
$.ajax({
url: "YourController/GetData",
type: "get",
data: $("form").serialize(), //if you need to post Model data, use this
success: function (result) {
$("#partial").html(result);
}
});
})
Then your action would look something like:
public ActionResult GetData(YourModel model) //that's if you need the model
{
//do whatever
return View(model);
}
Actually, if your Partial has a child action method, you can post (or even use an anchor link) directly to the child action and get an Ajax-like affect. We do this in several Views.
The syntax is
#Html.Action("MyPartial")
The Child Action is
public ActionResult MyPartial()
{
return PartialView(Model);
}
If your form posts to the child action
#using (Html.BeginForm("MyPartial"))
{
    ...
}
The Partial View will be updated with the partial view returned from the child action.
Jquery is still a legitimate way to update a partial. But technically, the answer to your question is YES.
As normal what I find when looking for things like this is people give too limited information so I will attempt to help here. The key is to set up a div with an ID you can append the return html to. Also when hitting your controller make sure it returns the partial. There are some potential problems with this method but on a good day it should work.
<div id="CategoryList" class="widget">
#{
Html.RenderPartial("WidgetCategories.cshtml");
}
</div>
function DeleteCategory(CategoryID) {
$.get('/Dashboard/DeleteWidgetCategory?CategoryID=' + CategoryID,
function (data) {
if (data == "No") {
alert('The Category has report widgets assigned to it and cannot be deleted.');
}
else {
$('#CategoryList').html(data);
}
}
);
}
[HttpGet("DeleteWidgetCategory")]
[HttpPost("DeleteWidgetCategory")]
public IActionResult DeleteWidgetCategory(string CategoryID)
{
string Deleted = CategoryModel.DeleteCategory(CategoryID);
if (Deleted == "Yes")
{
return PartialView("WidgetCategories");
}
else
{
return this.Json("No");
}
}
I would use the Ajax Form helper for such scenarios using a partial view and #html.RenderPartial("partialName")
partial helpers
In your Main View
<div id=SearchResult>
#Html.Partial("_NameOfPartialView", Model)
</div>
<input type="button" id="btnSubmit" value="Submit">
In your Javascript file
$('#btnSubmit').click(function () {
GetData(Id);
});
function GetData(Id){
$.ajax({
url: "/Home/GetEmployee/",
type: "get",
data: { Id:Id },
success: function (result) {
$('#SearchResult').html(result);
}
});
}
In your Home Controller
public ActionResult GetEmployee(int Id)
{
var employee= context.Employee.Where(x=> x.EmployeeId == Id)
return this.PartialView("_NameOfPartialView", employee);
}

How to Pass textbox value using #html.actionlink in asp.net mvc 3

How to Pass value from text using #html.actionlink in asp.net mvc3 ?
None of the answers here really work. The accepted answer doesn't refresh the page as a normal action link would; the rest simply don't work at all or want you to abandon your question as stated and quit using ActionLink.
MVC3/4
You can use the htmlAttributes of the ActionLink method to do what you want:
Html.ActionLink("My Link Title", "MyAction", "MyController", null, new { onclick = "this.href += '&myRouteValueName=' + document.getElementById('myHtmlInputElementId').value;" })
MVC5
The following error has been reported, but I have not verified it:
A potentially dangerous Request.Path value was detected
Rather than passing your value using #Html.actionlink, try jquery to pass your textbox value to the controller as:
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: { search: $('#textboxid').val()},
success: function (result) {
$('#mydiv').html(result);
}
});
return false;
});
});
This code will post your textbox value to the controller and returns the output result which will be loaded in the div "mydiv".
to pass data from the client to the server you could use a html form:
#using (Html.BeginForm(actionName,controllerName)) {
<input type="text" name="myText"/>
<input type="submit" value="Check your value!">
}
be sure to catch your myText variable inside your controller's method
you can use this code (YourValue = TextBox.Text)
Html.ActionLink("Test", new { controller = "YourController", action = "YourAction", new { id = YourValue }, null );
public class YourController : Controller
{
public ActionResult YourAction(int id)
{
return View("here your value", id);
}
}

Submit Data from partial view to a controller MVC

I have a list of employment records, you can also add an employment record from the same page using a partial view.
Heres employment.cshtml that has a partial view for the records list and a partial view to add a new record which appears in a modal pop up.
<h2>Employment Records</h2>
#{Html.RenderPartial("_employmentlist", Model);}
<p>
Add New Record
</p>
<div style="display:none">
<div id="regModal">
#{Html.RenderPartial("_AddEmployment", new ViewModelEmploymentRecord());}
</div>
</div>
Heres the partial view _AddEmployment.cshtml
#using (Html.BeginForm("AddEmployment, Application"))
{
#Html.ValidationSummary(true)
<div class="formEl_a">
<fieldset>
<legend></legend>
<div class="sepH_b">
<div class="editor-label">
#Html.LabelFor(model => model.employerName)
</div>
etc....etc....
</fieldset>
</div>
<p>
<input type="submit" class="btn btn_d" value="Add New Record" />
</p>
}
and heres my Application controller:
[HttpPost]
public ActionResult AddEmployment(ViewModelEmploymentRecord model)
{
try
{
if (ModelState.IsValid)
{
Add Data.....
}
}
catch
{
}
return View(model);
}
When compiling the following html is generated for the form:
<form action="/Application/Employment?Length=26" method="post">
It brings in a length string? and is invoking the Employment controller instead?
Hope all is clear....
QUESTION ONE: when I click the submit button from within the partial view it does not go to the controller specified to add the data. Can anyone see where im going wrong?
QUESTION TWO: When I get this working I would like to update the employment list with the new record....am I going about this the correct way? Any tips appreciated.
Answer 1: First try this and let me know if that hits your controller.
#using (Html.BeginForm("AddEmployment", "Application", FormMethod.Post))
Answer 2: To update the employment list, I would assume you would want to save the model to your database then have your employment list displayed on the same page or a different page calling the data from the DB into the the list or table to be displayed.
Edit:
It looks as though your form attributes are not being applied.
For your employment.cshtml, I personally don't use { } around my #Html statements.
You must not be doing what I stated above because your error occurs only when I write it as
#using (Html.BeginForm("AddEmployment, Application", FormMethod.Post))
missing those closing quotes is what is causing your problem.
jQuery code:
window.jQuery(document).ready(function () {
$('#btnsave').click(function () {
var frm = $("form");
var data = new FormData($("form")[0]);
debugger;
$.ajax({
url: '/Home/Update',
type: "POST",
processData: false,
data: data,
dataType: 'json',
contentType: false,
success: function (response) {
alert(response);
},
error: function (er) { }
});
return false;
});
});
Controller Code
[HttpPost]
public JsonResult Update(Generation obj)
{
if (ModelState.IsValid)
{
return Json("done");
}
else
{
return Json("error create");
}
}
Using those code you can post form using jquery and get response in jsonresult
I know this is very old Question
the reason it didn't work for you because your syntax
Here is your code
#using (Html.BeginForm("AddEmployment, Application"))
the fix
#using (Html.BeginForm("AddEmployment", "Application"))
Regards
you have put #using (Html.BeginForm("AddEmployment, Application")) what this is trying to do is invoke a action called "AddEmployment, Application" i think you meant #using (Html.BeginForm("AddEmployment", "Application"))

unobtrusive client validation in knockout template binding

I have a model with data annotations and i am an dynamically binding that with viewmodel using knockout template binding and mapping plugin. I am trying to do a unobtrusive client validation to be done on my model. How we can do that in this scenario. Any help/suggestions?
public class MyUser
{
[Required]
[StringLength(35)]
public string Username { get; set; }
[Required]
[StringLength(35)]
public string Forename { get; set; }
[Required]
[StringLength(35)]
public string Surname { get; set; }
}
In my view i am dynamically template binding a list of MyUser using ajax.
public JsonResult TestKnockout()
{
IList<MyUser> myUserList = new List<MyUser>();
myUserList.Add(new MyUser { Username = "ajohn", Surname = "surname" });
myUserList.Add(new MyUser { Username = "ajohn1", Surname = "surname1" });
return Json(myUserList, JsonRequestBehavior.AllowGet);
}
}
View:
<form id="Userform" action='#Url.Action("Save", "Home")' data-bind="template: {name: 'UserTemplate', foreach:UserList}">
<input type="Submit" name="name" value="Submit" />
</form>
<script id="UserTemplate" type="text/Html">
<input type="text" data-bind="value: Username"></input>
<input type="text" data-bind="value: Forename"></input>
<input type="text" data-bind="value: Surname"></input>
</script>
<script type="text/javascript">
var viewModel = {
UserList: ko.observableArray(new Array()),
Save: function () {
//// reached here means validation is done.
alert("Save");
}
}
ko.applyBindings(viewModel);
$.ajax({
type: 'GET',
url: '../Home/TestKnockout',
contentType: "application/json",
success: function (data) {
$.each(ko.mapping.fromJS(data)(), function () {
viewModel.UserList.push(this);
})
// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse("#Userform");
// bind the submit handler to unobtrusive validation.
$("#Userform").data("validator").settings.submitHandler = viewModel.Save;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
</script>
pilavdzice and drogon answers are quite good but we forget the basic point.
Since we are using an MVVM pattern for the seperation of UI and data (+vm) we don't want to perform UI validation but DATA VALIDATION. Those two are quite different, jquery validate is a great plugin but it does UI validation (it starts from UI to check the fields).
I have found knockout validation plugin which seems to do quite well and what it does is to go the opposite road, it validates your viewmodel and not your UI (it actually maps to UI elements to display the errors).
Unfortunately If your viewmodel gets complex, that plugin will have some problems, but in any case this is the way to go.
UI validation is perfect as long as we are not using an MVVM pattern, after all what do we separate the components (M-V-VM) for ?
Hope I helped !
Thanks!
I had the same problem as you so I wrote the following component.
https://www.nuget.org/packages/ScriptAnnotations/
https://scriptannotations.codeplex.com/
Please let me know if this helps.
I would go with jquery's event binding for this.
First, add your data-val attributes to the inputs you want to validate. (To figure out which data-val attributes to use, I usually bind a form server-side to a model and view source.)
<input data-val-required="test" data-val="true" data-bind="visible:
$parent.userEditMode, value: FirstName" />
Second, add a validation utility function --this calls the jquery validation plugin used by MVC under the covers.
function validateForm(thisForm) {
var val = thisForm.validate();
var isValid = val.form();
alert(isValid);
if (!isValid) {
thisForm.find('.input-validation-error').first().focus();
}
return isValid;
}
Third, call validate before issuing your viewmodel method. Make sure to remove the "click" data-bind attribute from the markup in your page.
$('#..your form id...').live('submit', function (e) {
e.preventDefault();
if(validateForm($(this)))
viewModel.saveUser();
});
If you are using knockoutjs and jquery, I came up with the following very simple method for doing basic validation.
Wherever you want to display the error message on your page, include a span tag like this:
<span name="validationError" style="color:Red"
data-bind="visible: yourValidationFunction(FieldNameToValidate())">
* Required.
</span>
Obviously you need to write "yourValidationFunction" to do whatever you want it to do. It just needs to return true or false, true means display the error.
You can use jquery to prevent a user from proceeding if any validations errors are displayed. You probably already have a save button that triggers a javascript function to do some ajax or whatever, so just include this at the top of it:
if ($("[name='validationError']:visible").length > 0) {
alert('Please correct all errors before continuing.');
return;
}
This is a lot simpler and more flexible than many other validation solutions out there. You can position your error message wherever you want, and you don't need to learn how to use some validation library.

Search and display on same page in mvc2 asp net

have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it.
Right now I'm doing the following but it's not working out exactly the way I want:
sathishkumar,
You don't tag the question as being an ajax related solution or not. I'm going to present a simple ajax approach which may or may not be suitable.
in the controller:
public ActionResult Search(string searchTerm)
{
// you don't add code re your stored proc, so here is a repo based approach
var searchItems = _repository.Find(x => x.searchfield.Contains(searchTerm));
return PartialView("SearchPartial", searchItems);
}
main view (index.aspx or whatever) (below where your main content is defined, add):
<div id="searchResults"></div>
in another part of the page (semi psuedo-code):
<script type="text/javascript">
function getSearchResults() {
// #yoursearchbox is a textbox on the index.aspx aview
var tdata = { searchTerm: $('#yoursearchbox').val()};
// or your data in the format that will be used ??
$.ajax({
type: "GET",
data: tdata,
url : '<%= Url.Action("Search", "Home") %>',
success: function (result) { success(result); }
});
});
function success(result){
$("#searchResults").html(result);
}
</script>
You'd then add a partial view SearchPartial.ascx that contained your model for the search results.
Hope this helps.
You can use Ajax to solve the problem.
<div>
`#using (Ajax.BeginForm("action", "controller", new AjaxOptions
{
UpdateTargetId = "results",
HttpMethod = "GET",
}))
{
#Html.TextBox()
<input type="submit" value="Search" />
}`
<div id="results"></div>
</div>

Resources