Reputation: 1181
I have a jquery script which does ajax call to my action inside the controller in my MVC application:
$('#save').click(function () {
$.post(url, { id: id, text: textarea.val() }, function (data) {
if (data) {
row.children('td').eq(3).text(textarea.val());
row.children('td').eq(4).text('Da');
row.children('td').eq(5).hide();
$('#napomena').val('');
form.hide();
}
});
});
And this is my controller:
public ActionResult PravdanjeIzostanaka(string id, string text)
{
var obj = db.Odsutnost.Find(Convert.ToInt32(id));
if(obj!=null && text.Trim()!="")
{
obj.Napomena = text;
obj.Opravdano = true;
db.SaveChanges();
return RedirectToAction("PregledIzostanaka");
}
return null; // what am I supposed to return here so that data type in ajax would be undefined??
}
As you can see im checking whether the obj object and text field are !=null and if its empty. If those two requirements are not met I would like to make a little alert which would basically say: "Text field is required!" and modify my script to something like this:
if (data!=="undefined") {
row.children('td').eq(3).text(textarea.val());
row.children('td').eq(4).text('Da');
row.children('td').eq(5).hide();
$('#napomena').val('');
form.hide();
}
else{
alert('Text field is required!');
}
So I need to modify my script and Action(action should return something which ajax would see it as undefined in order that I can do alert)...
Can someone help me out with this? :)
Upvotes: 2
Views: 960
Reputation: 171
Just return a json string as undefined. More like the below:
public ActionResult PravdanjeIzostanaka(string id, string text)
{
var obj = db.Odsutnost.Find(Convert.ToInt32(id));
if(obj!=null && text.Trim()!="")
{
obj.Napomena = text;
obj.Opravdano = true;
db.SaveChanges();
return RedirectToAction("PregledIzostanaka");
}
return json("undefined");
}
Upvotes: 1