I choose from dropdown menu an item and click add => ajax call a method which return JsonResult this is all ok. Then this data should be send to another function PartialViewResult on server side: public PartialViewResult _SkupinaRow(skupinaRow skupinaRow), which generate a new tr with some textbox and labels. My problem is that no binding is made. I get Null when debuggin in _SkupinaRow(skupinaRow skupinaRow)
I have the following domain model defined:
public class skupinaRow
{
public BONUSMALUS bonusmalus { get; set; } //items
public KOLEDAR koledar { get; set; } //calendar
}
Partial View:
#model ObracunPlac.ViewModel.skupinaRow
#Html.HiddenFor(x => x.bonusmalus.bon_id)
.....
Partial view code:
public PartialViewResult _SkupinaRow(skupinaRow skupinaRow)
{
return PartialView("_SkupinaRow", skupinaRow);
}
Ajax Call:
$("#addItemPrihodki").live("click", function () {
var id = $("#prihodkidodaj option:selected").val()
var skupinaRow = {
bonusmalus:{},
koledar:{}
}
jQuery.getJSON("/Placa/getBonusMalus/?id=" + id, function (data) {
console.log("JSON Data: " + data.koledar.kol_id);
skupinaRow.koledar.kol_id = data.koledar.kol_id, //ok
skupinaRow.bonusmalus.bon_id = data.bonusmalus.bon_id, //ok
//alert(JSON.stringify(GetBonusMalusModel($("#bonusdodaj option:selected").val())));
alert(JSON.stringify(data));
// alert(skupinaRow.serialize());
$.ajax({
url: "../_skupinaRow",
cache: false,
data: JSON.stringify(skupinaRow),
//data: JSON.stringify(data),
datatype: JSON,
success: function (html) {
$("#editorRowPrihodki table tr#dodajNov").before(html);
}
,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error'+"+++"+textStatus+"--- "+errorThrown);
},
});
});
return false;
});
public JsonResult getBonusMalus(int id)
{
KOLEDAR koledar = db.KOLEDAR.Single(r => r.kol_id == KoledarID);
BONUSMALUS bm = db.BONUSMALUS.Single(r => r.bon_id == id);
skupinaRow model = new skupinaRow
{
koledar =koledar,
bonusmalus = bm
};
// return Json result using LINQ to SQL
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = model
};
}
Debug picture: https://www.dropbox.com/s/189q080irp0ny77/1.jpg
This worked when i had one model bonusmalus but now I ned two so I created modelView.
How can I bind ViewModel-SkupinaRow to Partial View with strong type SkupinaRow ?
If you are using AJAX only to convert he value to json? then you can use this approach
Set the form with normal post back to Action in controller
use jQuery in your view and on submit of form write this.
$("form").submit(function(){
$("#DropDown_Items").val(JSON.stringify(data));
});
Now you can use this in your Action Method.
Related
I am trying to reload my Partial View _Home when I close my dropdown. Currently I can get that dropdown value to call another method and do the logic that will change the model then send the model back to the index. However, I cannot get my _Home Partial View to reload and actually take in this new model. I cannot seem to be able to actually call the public ActionResult _Home(Model model) method. I am wondering how to pass in this new model and refresh the partial view.
I have tried to pass in the model to the partial view but this seems to have no effect, having no model being passed in does not change anything either. I have seen a few examples online of how to refresh partial views but none of them pass in any parameters.
JavaScript
function OnClose() {
var chart = $("#safetyIncident-chart").data("kendoChart");
var chart2 = $("#qualityError-chart").data("kendoChart");
chart.dataSource.read();
chart2.dataSource.read();
var selectProductionLine = $("#productionLine-dropdown").data("kendoDropDownList").value();
$.ajax({
url: '#Url.Action("UpdateView", "Home")', //Updates model and then calls Index
type: 'post',
dataType: "json",
data: { "selectProductionLine": JSON.stringify(selectProductionLine) }, //Passes in DropDownValue correctly
success: function (data) {
$("#partial").html(result);
$("#Dashboard").load("/Home/_Home"); //Trying to reload the partial view
}
});
}
View
<div id="Dashboard">
#Html.Partial("~/Views/Home/_Home.cshtml")
</div>
Controller
[HttpGet]
public ActionResult Index()
{
DisplayViewModel dvm = (DisplayViewModel)TempData["dvm"];
if(dvm != null)
{
return View(dvm);
}
//Initializes new dvm if previous was null
return View(dvm);
}
I am trying to refresh my partial view once DropDown closes and the ViewModel is refreshed.
EDIT:
UpdateView method in Controller
[HttpPost]
public ActionResult UpdateView(string selectProductionLine)
{
if(selectProductionLine == null)
{
selectProductionLine = _productionLineService.Collection().FirstOrDefault().Id;
}
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(selectProductionLine, typeof(string));
DisplayViewModel dvm = new DisplayViewModel();
ProductionLine pl = _productionLineService.Find(jsondata);
dvm.ProdLine = new ProductionLineViewModel
{
Id = pl.Id,
CreatedAt = pl.CreatedAt,
Name = pl.Name,
ActiveLine = pl.ActiveLine,
ComputerName = pl.ComputerName,
UPE = pl.UPE
};
TempData["dvm"] = dvm;
return Index();
//PartialView("~/Home/_Home.cshtml", dvm);
}
I am making a live search, where a user types something inside a text box and then via ajax results are fetched and added to a ul and in this specific case I am looking for usernames, so if a username is johnny and the user types in jo then johnny should come up and so on.
I have the ajax js code, a post method and a list model view of users, I am now trying to return the list but doesn't seem to be working.
my js:
$("input#searchtext").keyup(function (e) {
var searchVal = $("input#searchtext").val();
var url = "/profile/LiveSearch";
$.post(url, { searchVal: searchVal }, function (data) {
console.log(data);
});
});
LiveSearch view model
public class LiveSearchUserVM
{
public LiveSearchUserVM()
{
}
public LiveSearchUserVM(UserDTO row)
{
FirstName = row.FirstName;
LastName = row.LastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}
the post method
[HttpPost]
public List<string[]> LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return usernames;
}
So basically I want to return a list (or something else) of columns that contain a specific string, and pass all the results to javascript thru ajax callback.
To return the result as JSON alter your method to the following:
[HttpPost]
public JsonResult LiveSearch(string searchVal)
{
// Init db
Db db = new Db();
List<LiveSearchUserVM> usernames = db.Users.Where(x => x.Username.Contains(searchVal)).Select(x => new LiveSearchUserVM(x)).ToList();
return Json(usernames);
}
you can use like this . The idea is to use success funtion
$.ajax({
url : ""/profile/LiveSearch"",
type: "POST",
data : searchVal ,
success: function(data)
{
//data - response from server
},
error: function ()
{
}
});
and return JsonResult from Post method
i have this return come from here
public string Get(int id)
{
return "{\"longPachage\":{\"Id\":0}}";
}
and i Receive this return by ajax with this code
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
alert(data);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})
what i can to deserialize json object and print the Id value only ?
You can use this code. It may be help to you.
You are not parse the data to get JSON in string format. So you can now use this code to get JSON data in string format.
var obj = JSON.parse(data);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var obj = JSON.parse(data);
alert(obj.Id);
alert(" Success ");
},
error: function (data) {
alert(" Error ");
}
})
yes, Stephen is right.
you have to send a json result from controller.
for exa.
public JsonResult Get(int id)
{
return Json(new
{
longPachage = new { ID = 0 }
}, JsonRequestBehavior.AllowGet);
}
and in your ajax success, just retrieve that object or dataID.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:3148/api/values/5",
success: function (data) {
var dataID = data.longPachage.Id;
// Do with Your ID.
},
error: function (data) {
//Do anything for error here.
}
})
Change your method like this:
public ActionResult Get(int? id)
{
return Content("{\"longPachage\":{\"Id\":0}}");
}
And then in your jQuery:
$.getJSON("http://localhost:3148/api/values", {id:5}, function(data) {
var id = data.longPachage.Id;
alert(id)
});
Try to use JsonResult in MVC to return Json instead of building a string. JsonResult is just an abstact class of ActionResult. Modify your code in the controller as follows
Method 1:
public JsonResult GetTest(int id)
{
return this.Json(new { ID = 0 }, JsonRequestBehavior.AllowGet);
}
OR
Method 2:
Try to create a model class as LongPachage
public class LongPachage()
{
public int ID {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
LongPachage model = new LongPachage();
model.ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
OR
Method 3
Create Model class say TestModel and try to add LongPachage class as propery of this class.
public class TestModel()
{
public LongPachage LongPachage {get;set;}
}
and try to invoke into the controller method as follows
public JsonResult Get(int id)
{
TestModel model = new TestModel();
model.LongPachage .ID = 0;
return this.Json(model, JsonRequestBehavior.AllowGet);
}
and then in the view using AJAX GET wrapper try to implement as follows
$.get('#Url.Action("Get","ControllerName")', { id: "5" })
.done(function (data) {
// If you are using Method 1 or Method 2 alert will be as follows
alert(data.ID);
// If you are using method 3
alert(data.LongPachage.ID)
});
I have the following JQuery method for posting data to a action in my MVC contorller:
$('#btnAddNewTest').on("click", function () {
var date = $('#HIVTestTestDate').val();
var result = $('#HIVTestTestResult').val();
var cd4 = $('#HIVTestCD4Count').val();
var pID = $('#PatientID').val();
var dataToSend = { patientID: pID, testDate: date, resultID: result, cd4Count: cd4 };
$.post("/HIVInformation/AddHIVTest/", dataToSend, function (receivedData) {
location.reload(false); //Don't want to do this
});
return false;
});
Here is the Action method in my controller:
[HttpPost]
public ActionResult AddHIVTest(Guid patientID, DateTime testDate, Guid resultID, int cd4Count)
{
MvcPatientDetailsHIVViewModel model = new MvcPatientDetailsHIVViewModel(patientID);
model.LoadAllData();
try
{
//add the HIV Test
model.HIVTestResult = new Common.Models.PatientHIVTestModel()
{
ID = Guid.NewGuid(),
PatientID = patientID,
TestDate = testDate,
HIVTestResultID = resultID,
CD4Count = cd4Count
};
//call the add method
model.AddHIVTestResults();
}
catch (Exception ex)
{
ModelState.AddModelError("", ex);
}
return View("Details", model);
}
If I comment out the 'location.reload(false);' my page does not get refreshed. How do I serialize my Mvc view to be returned in the function (receivedData) delegate of the post? How do I display my view then from within the JQuery code?
if i may, i would suggest to you to use ajax, partial views, and a container div for example to load the result in it.
Example:
Script:
$(document).ready(function () {
$("#btnAddNewTest").on("click", function () {
$.ajax({
url: '#Url.Action("YourAction", "YourController")',
type: 'post',
data: {
yourData1: value1,
yourData2: value2,
},
success: function (result) {
$('#dynamicContent').html(result);
}
});
});
});
Controller:
public ActionResult YourAction(int yourData1= 1, int yourData2 = 0)
{
return PartialView("~/yourviewPath/_YourPartialView.cshtml", yourResultModel)
}
Html:
<div id="dynamicContent" class="Float_Clear">
#Html.Partial("~/yourviewPath/_YourPartialView.cshtml", Model)
</div>
Live example that I created using the same concept here
Suppose I have a Action which return a JsonResult. Like below code:
public ActionResult testAction()
{
return Json(new { name="mike",age="20"});
}
It json an anonymous object and return it. Then I want to write below code in View (.cshtml) file with razor engine.
#{
JsonResult m = ///some method can help me get the JsonResult
//Then I can print the value of m
#m.Data.ToString()
}
How to do it?
why do you use json result in view? You can:
public ActionResult testAction()
{
return View(new Model{ name="mike",age="20"});
}
In your View, you can call your testAction method via an Ajax call, then access to your returned object. But as far as I know, you must return a model.
Create a Model
public class YourModel
{
public string Name { get; set; }
public int Age { get; set; }
}
A Controller :
public ActionResult testAction(string name, int age)
{
YourModel ym = new YourModel();
ym.Name = name;
ym.Age = age;
return Json(ym, JsonRequestBehavior.AllowGet);
}
Your View :
var name = "Mike";
var age = "20";
$.ajax({
url : "#Url.Action("testAction", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({name: name, age: age})
}).done(function (data) {
alert(data); // Do what you want with your object, like data.Name
})
This is a dummy example because you pass parameter from the view to the controller, then send them back to the view, but I think this sample can help you to better understand how to play with Ajax call in ASP.NET MVC3. Ajax call is asynchronous, but thank to deferred .done, you wait for the end of the server call to ensure your data object is filled
You have to use ajax to read.
$.ajax({
url: "/YourController/testAction/",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: json,
type: 'POST',
success: function (data) {
setTimeout(function () {
//find your html element and show.
$("#ShowSomewhere").val(data.name);
}, 500);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
try use Html.Action("actionName");
this return a string