I am writing ASP.NET web application. I am using views generated by Visual Studio (Create/Delete/Details/Edit/Index). In my application I have Articles which can be commented by logged users. Everything works fine (adding comment and viewing it), but to view newly added comment I have to manually refresh page.
Structure of Article/Details View looks like:
#if (Request.IsAuthenticated)
{
using (Ajax.BeginForm("Create", "Comment", new { articleId = Model._article.ArticleId }, new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDisplayID"
}))
{
#Html.ValidationSummary(true)
<fieldset>
<h4>Dodaj komentarz</h4>
<p>
#Html.TextArea("komentarz", new { #class = "form-control" })
</p>
<p>
<input type="submit" value="Dodaj" class="btn btn-primary btn-large" />
</p>
</fieldset>
}
}
else
{
<p>
Zaloguj się aby dodać komentarz.
</p>
}
<hr />
<div id="myDisplayID">
#Html.Partial("_Comment", Model._comment)
</div>
EDIT
Comment/Create GET method
public ActionResult Create(int articleId)
{
var komentarz = new Comment();
komentarz.ArticleId = articleId;
return View(komentarz);
}
Comment/Create POST
[HttpPost]
public ActionResult Create(Comment comment, string komentarz, int articleId)
{
if (komentarz != String.Empty)
{
if (ModelState.IsValid)
{
comment.UserId = (int)WebSecurity.GetUserId(User.Identity.Name);
comment.Content = komentarz;
comment.ArticleId = articleId;
db.Comments.Add(comment);
db.SaveChanges();
}
}
ArticleViewModel widok = new ArticleViewModel();
widok._comment = (from b in db.Comments where b.ArticleId == articleId select b).ToList();
return PartialView("_Comment", widok._comment);
}
Article/Details GET method
public ActionResult Details(int id = 0)
{
ArticleViewModel widok = new ArticleViewModel();
widok._comment = (from b in db.Comments where b.ArticleId == id select b).ToList();
widok._article = (from t in db.Articles where t.ArticleId == id select t).FirstOrDefault();
if (Request.IsAjaxRequest())
{
return PartialView("_Comment", widok._comment);
}
if (widok == null)
{
return HttpNotFound();
}
return View(widok);
}
If you are to use Ajax.BeginFrom like you have shown. (but with some modifications)
using (Ajax.BeginForm(new AjaxOptions {
HttpMethod= "get",
InsertionMode=InsertionMode.Replace,
UpdateTargetId = "myDisplayID"
}))
, there are 3 things you need.
your comment section should be in a partial view and strongly type it (for your solution it might be a list of comments)
you should check if the request is ajax within the Action, using 'Request.IsAjaxRequest()'
if it's an ajax request, then you should return a partial view not the view.
.
public ActionResult Details()
{
//what ever the data retrieve code you have
return View(alldata);
}
[HttpPost]
public ActionResult Create(Comment comment, string komentarz)
{
if (komentarz != String.Empty)
{
if (ModelState.IsValid)
{
comment.UserId = (int)WebSecurity.GetUserId(User.Identity.Name);
comment.Content = komentarz;
db.Comments.Add(comment);
db.SaveChanges();
}
}
ArticleViewModel widok = new ArticleViewModel();
widok._comment = (from b in db.Comments where b.ArticleId == id select b).ToList();
return PartialView("_Comments",widok._comment);
}
submit comment - view
using (Ajax.BeginForm("Create", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDisplayID"
}))
{
#Html.ValidationSummary(true)
<fieldset>
<h4>Dodaj komentarz</h4>
<p>
#Html.TextArea("komentarz", new { #class = "form-control" })
</p>
<p>
<input type="submit" value="Dodaj" class="btn btn-primary btn-large" />
</p>
</fieldset>
}
in your view
instead of
<h4>Comments</h4>
<table>
// table with comments for this article
</table>
put
<div id="myDisplayID">
#Html.Partial("_Comments", Model.Comments)
</div>
_Comments partial view
#model IEnumerable<Comments>
<h4>Comments</h4>
<table>
// table with comments for this article
</table>
I think doing it this way will improve the user experience if you also happen to add new comments using ajax
You can refresh in javascript with window.location.href=window.location.href. Reload posts the data again.
Best option to do this send a post request with an ajax Call, like this:
var comment = $("#txtComment).val(); // change this id with your textarea id
var id = #Model._article.ArticleId;
$.ajax({
url: "/Comment/Create",
type: "POST",
dataType: "json",
data: JSON.stringify({ content: comment, articleId: id }),
contentType: "application/json; charset=utf-8",
success: function (data) {
// if you returning all your comment use this
$("table").html(data.allContent);
// or if you return just a row with this comment
$("table").prepend(data.Comment);
}
I assume your Action method like this:
[HttpPost]
public ActionResult Create(string content,int articleId)
{
...
return Json(new { allContent = comments }); // just for example
}
Problem solved with changing
return View()
in POST Create Action to
ControllerContext.HttpContext.Response.Redirect(ControllerContext.HttpContext.Request.Url.ToString());
without any Partial Views, AJAX and Jquery
Try this :
return RedirectToAction("Index", "Comments");
or however your controller is called. But..
The best solution for me is to add comment asynchronously with jquery ajax. Comment/Create should return html as response (partialview), and you should replace old table with new one.
$.ajax({
url: "Comments/Create",
data: {comment : "bla bla", articleId : 1},
success: function (response) {
if (response == 'True') {
$('table').html(response);
}
}
});
Check some jquery ajax tutorials, it's very useful for such things. You can also use javascript when you are firing the action, which will prepare some html code with another row, and append it to table. Both of these ways are very nice, because you are not forced to reload the page.
Related
My project consists on making an OCR read on an image from coordinates drawn by the user.So i have made 2 external javascripts one manipulates the rectangles and the second manipulates the file(delete, preview..)
FileUpload.JS
function saveImage() {
var file = $("#imageBrowser").get(0).files;
var data = new FormData;
data.append("ImageFile", file[0]);
$.ajax({
async: true,
type: "POST",
dataType: "JSON",
url: "/OcrImage/OcrOnImage",
data: data,
processData: false,
contentType: false,
})
}
RectangleDrawing.js
$(function () {
$('#btnSend').click(function (e) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(boundingBoxes),
url: "/OcrImage/OcrOnImage",
});
});
});
the Controller
[HttpPost]
public ActionResult OcrOnImage(ImageUploadModel objeImageViewModel, Coordinate[] Coordinates)
{//code}
My question is how can i pass data from each javascripts to a single controller through a single submit.Keep in mind that i have tried to upload the file using razorview and i could pass only one data which is either Coordinates or the file to upload.
If there's a better method to do this please let know with an example.Thank you in advance.
I can provide more info if not clear.
If you want to file upload with view models (in your case ImageUploadModel) then you need to consider two things.
Your view model should contains a property of type HttpPostedFileBase like below:
HttpPostedFileBase ImageUpload { get; set; }
You should have strongly typed view with model bindings. something like below:
#model ImageUploadModel
<form action="" method="post" enctype="multipart/form-data">
<div>
#Html.LabelFor(m => m.ImageUpload)
#Html.EditorFor(m => m.ImageUpload)
</div>
<button type="submit">Create</button>
You could use #using (Html.BeginForm()) { ... } helper alternative to using form if you want to but for fileupload you must have this enctype="multipart/form-data" attribute.
Controller code would be like below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult OcrOnImage(ImageUploadModel model)
{
var validImageTypes = new string[]
{
"image/gif",
"image/jpeg",
"image/pjpeg",
"image/png"
}
if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
{
ModelState.AddModelError("ImageUpload", "This field is required");
}
else if (!imageTypes.Contains(model.ImageUpload.ContentType))
{
ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
}
if (ModelState.IsValid)
{
var image = new Image
{
Title = model.Title,
AltText = model.AltText,
Caption = model.Caption
}
if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
{
var uploadDir = "~/uploads"
var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
var imageUrl = Path.Combine(uploadDir, model.ImageUpload.FileName);
model.ImageUpload.SaveAs(imagePath);
image.ImageUrl = imageUrl;
}
db.Create(image);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
I have never faced like this situation where file upload and another action is going with along , it is some violation of SRP (single responsibility principle). By the way you can try coordination with js as you described above on putting Coordinate list/array in controller action like below and let me is that works or not.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult OcrOnImage(ImageUploadModel model,Coordinate[] Coordinates) {//like above}
I'm using ASP.NET MVC, and I'm trying to build a voting system, similar to stackoverflow.
I want that when I click on voteup button, to make a post on an action, make some checks there, but to remain on my initial page, and increment the vote (with js), if the checks passed (just like SO).
The items that I want to vote are populated by Index Action
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div><input type="submit" name="Vote" value="" class="fa fa-angle-up"/>
</div>
<div>#Html.DisplayFor(modelItem => item.Votes)</div>
<div><input type="submit" name="Vote" value="" class="fa fa-angle-down" /></div>
}
Action
public ActionResult SendVote(string vote)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<VoteLogViewModel, VoteLog>());
var mapper = config.CreateMapper();
switch (vote)
{
case "":
if (ModelState.IsValid)
{
//Send to db
VoteLogViewModel voteLogViewModel = new VoteLogViewModel
{
DateAdded = DateTime.Now,
Id = Guid.NewGuid().ToString(),
PlaceId = id,
UserId = User.Identity.GetUserId(),
Vote = 1
};
db.VoteLogs.Add(mapper.Map<VoteLog>(voteLogViewModel));
db.SaveChanges();
}
else
{
return RedirectToAction("Index");
}
break;
case "":
if (ModelState.IsValid)
{
//Send to db
}
else
{
return RedirectToAction("Index");
}
break;
}
return new EmptyResult();
}
How do I vote, without reloading the whole page?
Should I just make some links under my voting icons and somehow handle this with routes?
What you need to do is use Ajax
Example:
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div><input type="submit" name="Vote" value="true" class="fa fa-angle-up"/>
</div>
<div>#Html.DisplayFor(modelItem => item.Votes)</div>
<div><input type="submit" name="Vote" value="false" class="fa fa-angle-down" /></div>
}
<script>
$(function(){
$('input[name="Vote"]').click(function(e){
e.preventDefault();
var result = e.data.value;
$.ajax({
type: "POST",
url: url // ActionURL,
data: result,
success: function(data) { //Success here },
});
});
});
</script>
Controller
public ActionResult SendVote(bool vote)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<VoteLogViewModel, VoteLog>());
var mapper = config.CreateMapper();
if(!ModelState.IsValid)
{
return RedirectToAction("Index");
}
if(vote)
{
//Send to db
VoteLogViewModel voteLogViewModel = new VoteLogViewModel
{
DateAdded = DateTime.Now,
Id = Guid.NewGuid().ToString(),
PlaceId = id,
UserId = User.Identity.GetUserId(),
Vote = 1
};
db.VoteLogs.Add(mapper.Map<VoteLog>(voteLogViewModel));
db.SaveChanges();
}
else
{
//Send to db
}
return new EmptyResult();
}
Please note it might not be syntactically correct since I wrote it in outside of an IDE. But this should get you going.
I also refactored your controller to use a boolean rather than switching on a string.
You're currently performing a full postback as in essence the HTML helper in your view is rending a standard HTML form.
You will need to trigger an AJAX post to the server if you don't want the whole page to refresh. If you are already including jQuery on your page, something like the following should work:
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '#Url.Action(your action method)',
data: {
//form variables here
},
dataType: 'JSON',
contentType: 'application/json',
success: function(result) {
//handle success
},
error: function(result) {
//handle error
}
});
});
I have a situation where I need to call ParentView from its partial view. Like I have list of ToDos in Partial view where Ajax actionlink is used to edit the data in parent by passing its id. The same is working without using Ajax as it is manipulating url by putting querystring. But we would like to have internal call with Ajax which is not firing.
The code we are using is like that:
<li>#Ajax.ActionLink(#item.ToDoTitle, "Index", new { tdid = #item.ToDoId }, new AjaxOptions { UpdateTargetId = "saved", InsertionMode = InsertionMode.Replace, HttpMethod="POST" })</li>
and controller is like that:
public ActionResult Index(int tdid =0)
{
if (tdid !=0)
{
ToDo t = new ToDo();
t.ToDoTitle = "Ramlal";
t.ToDoDesc = "Shyamlal";
t.ToDoId = tdid;
return Json(t);
}
else
{
return View();
}
}
We have tried the same with returning a view but nothing have happened, so we have tried to use Json as it returning model.
Correct me if I am wrong?
FYI, this is the parent view:
#model myTask.Models.ToDo
#{
ViewBag.Title = "My Task";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
#using (Ajax.BeginForm("Save", new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "MyTaskList" }))
{
#Html.AntiForgeryToken()
<div class="MyTask">
#Html.HiddenFor(t => t.ToDoId)
<div class="row">
<div class="col-lg-12">
#Html.LabelFor(t => t.ToDoTitle)<br />
#Html.TextBoxFor(t => t.ToDoTitle)
</div>
<div class="col-lg-12">
#Html.LabelFor(t => t.ToDoDesc)<br />
#Html.TextAreaFor(t => t.ToDoDesc)
</div>
</div>
<script>
$( "#ToDoTitle" ).blur( function() {
$.ajax({
url: "Save",
type: "POST",
data: $("#form0").serialize(),
dataType: "json"
}).done(function (model) {
$("#ToDoId").val(model.ToDoId);
$("#ToDoTitle").val(model.ToDoTitle);
$("#ToDoDesc").val(model.ToDoDesc);
});
});
$("#ToDoDesc").blur(function () {
if ($("#ToDoId").val() > 0) {
$.ajax({
url: "Save",
type: "POST",
data: $("#form0").serialize(),
dataType: "json"
}).done(function (model) {
$("#ToDoId").val(model.ToDoId);
$("#ToDoTitle").val(model.ToDoTitle);
$("#ToDoDesc").val(model.ToDoDesc);
});
}});
</script>
</div>
<div class="ObjectList" id="MyTaskList">
#Html.Action("TodoList")
</div>
<div class="clearfix"></div>
}
This is partial view which is being called using #Html.Action("TodoList")
#using System.Linq
#model myTask.Models.ToDoList
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div class="row">
#if (Model.ToDos.Count > 0)
{
<ul>
#foreach (var item in Model.ToDos)
{
#*<li>#Html.ActionLink(#item.ToDoTitle, "Index", new { tdid = #item.ToDoId })</li>*#
<li>#Ajax.ActionLink(#item.ToDoTitle, "/Index", new { tdid = #item.ToDoId }, new AjaxOptions { UpdateTargetId = "MyTask", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" })</li>
}
</ul>
}
</div>
Controller:
using myTask.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace myTask.Controllers
{
public class TasktdController : Controller
{
// GET: Tasktd
public ActionResult Index(int tdid =0)
{
if (tdid !=0)
{
ToDo t = new ToDo();
t.ToDoTitle = "Ramlal";
t.ToDoDesc = "Shyamlal";
t.ToDoId = tdid;
return PartialView(t);
}
else
{
return View();
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Save(ToDo td)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
ModelState.Remove("ToDoId");
if (ModelState.IsValid)
{
var t = await td.Save(td);
return Json(td);
}
return Json("Oops! Error Occured");
}
[ChildActionOnly]
public PartialViewResult TodoList()
{
ToDoList tdl = new ToDoList();
List <ToDo> tds= new List<ToDo>();
ToDo t = new ToDo();
t.ToDoId = 1;
t.ToDoTitle = "XXX";
tds.Add(t);
tdl.ToDos = tds;
return PartialView(tdl);
}
}
}
There a number of problems with your code. First your submitting the form using .ajax() - and the form does not even have a submit button anyway! Replace
#using (Ajax.BeginForm("Save", new AjaxOptions() { ... })
{
....
}
with
<form id="form">
.... // add controls for properties
<button id="save" type="button">Save</button>
</form>
and remove the scripts for $( "#ToDoTitle" ).blur() and $("#ToDoDesc").blur() and replace with
<script>
var form = $('#form');
var saveUrl = '#Url.Action("Save")';
$.post(saveUrl, form.serialize(), function(data) {
if(data) {
// save successful - give the user some feedback
}
}).fail(function (result) {
// Oops and error occurred - give the user some feedback
});
.... // add script for editing here (see below0
</script>
Your current scripts result in poor performance and are the result of a bad UI design. The user should decide when to save (i.e by clicking a button), not you. Consider what happens if the user edits the title and tabs to the description then realizes that all was correct and nothing needed to be changed afterall (you code has already altered the data in the database and the user would not even know it)
Note the script should be immediately before the closing </body> tag (not inline). And the Save() method should return Json(true) if the objects was successfully saved.
To handle clicking the 'links', change the partial to (note the #if block it not required)
<ul>
#foreach (var item in Model.ToDos)
{
<li>
<span>#item.ToDoTitle</span>
<button class="edit" type="button" data-id="#item.#item.ToDoId">Edit</button>
</li>
}
</ul>
And if you want the button to look like a link, then use css to style it
Then add another script in the main view
var editUrl = '#Url.Action("Get")';
$('.edit').click(function() {
var id = $(this).data('id');
var title = $(this).prev('span').text();
$.getJSON(editUrl, { id: id, function(data) {
// Populate form fields
$('#ToDoId').val(id);
$('#ToDoTitle').val(title);
$('#ToDoDesc').val(data);
});
});
And the controller method would be
public JsonResult Get(int id)
{
// Look up the Description based on the id, for example
string description = db.ToDo.Where(x => x.ToDoId == id).Select(x => x.ToDoDesc);
return Json(description, JsonRequestBehavior.AllowGet);
}
Note, you already have the ID and Title properties in the view so its only necessary to return the Description (and I suggest you change your property names as suggested here - i.e. ID, Title and Description)
I have a simple create form in MVC 4 and would like two submit functions: (1) Create and (2) Create & Print. Create is a normal Create action and works perfectly. Create & Print should save the object and then launch a popup browser window with data from the newly saved object. The original window needs to refresh to a blank Create form ready for another record.
What is the best way to approach this?
Below is an example that works in practice however I have the ID hardcoded in. Ideally, this ID will dynamically inherit from the object that was just saved and link there. Is JavaScript the best idea here or should (can) I launch the popup from the Controller?
<input type="submit" value="Create" />
<input type="submit"
value="Create & Print"
onclick="window.open('Print/f1ad6330-2978-4ea9-9116-65f861412260'
, 'PRINT'
, 'height=200,width=200');" />
Best option is to create another action which returns string (last-insert-id), post data to it through ajax and get last-insert-id back in javascript then you can use it to open new window.
Now suppose this is new controller action:
[HttpPost]
public string CreateAndPrint(Object obj)
{
// Save data here / insert record here
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = db.GetLastInsertId; // get last insert id from database
return lastInsertId;
}
}
Have a javascript function to post the data:
<script type="text/javascript">
function creteAndPrint() {
$.ajax(
{
url : "CreateAndPrint",
type: "POST",
data : $("#from1").serialize(),
success:function(data)
{
var lastInsId = data; // you will get last insert id here.
var secWin = window.open('Print/'+lastInsId
, 'PRINT'
, 'height=200,width=200');
secWin.focus();
}
});
}
</script>
And call this function only on create & print button:
<input type="submit" value="Create & Print" onclick="creteAndPrint();" />
Hope it works for you. Thank you.
Here I am editing my answer after your comment :)
Yes! you can call the same Create action for achieving the same which I explained above. But for that you have to make some changes in the your Create action:
public string Create(Object obj)
{
// Save data here / insert record here
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = db.GetLastInsertId; // get last insert id from database
return PartialView("_Create", lastInsertId);
}
return View();
}
Notice that when you call this action through AJAX it will return a partial view, which return just LAST_INSERT_ID as string. You just have create one simple partial view _Create to print last-insert-id.
Partial view will have only two lines:
#model string
#Model
This will print the last-inst-id which we have passed from controller action.
I ended up bypassing the form's default submit call to the Create method and just created two new methods. It's not ideal, but it works.
SOLUTION
Form:
#using (Html.BeginForm("Dummy", "Count", FormMethod.Post, new { id = "form1" }))
{
// My Form
// Note the Dummy controller which will just fall through and do nothing
}
Form Submit:
<input type="submit" value="Create & Print" onclick="createAndPrint();" />
<input type="submit" value="Create" onclick="createWithoutPrinting();" />
JavaScript:
<script type="text/javascript">
function createAndPrint() {
$.ajax(
{
url: "CreateAndPrint",
type: "POST",
data: $("#form1").serialize(),
success: function (data) {
var lastInsId = data; // you will get last insert id here.
var secWin = window.open('Print/' + lastInsId
, 'PRINT'
, 'height=450,width=230');
secWin.focus();
}
});
}
</script>
<script type="text/javascript">
function createWithoutPrinting() {
$.ajax(
{
url: "Create",
type: "POST",
data: $("#form1").serialize()
});
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Dummy(Count count)
{
return RedirectToAction("Create");
}
[HttpPost]
public string CreateAndPrint(Count count)
{
SaveCount(count);
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = count.Id.ToString();
return lastInsertId;
}
return "";
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Count count)
{
SaveCount(count);
if (Request.IsAjaxRequest())
{
// Now get last insert id
string lastInsertId = count.Id.ToString();
return PartialView("_Create", lastInsertId);
}
return RedirectToAction("Create");
}
I'm new to MVC(Asp.net) as well as JavaScript. sorry for this primary question.
<body>
<div>
<%--<% Html.BeginForm(); %>--%>
<table>
<tr>
<td><%:Html.LabelFor(t=> t.CustomerID) %></td>
<td><%:Html.TextBoxFor(t => t.CustomerID, new { ID = "txtCustomerID" })%></td>
</tr>
<tr>
<td><%:Html.LabelFor(t=> t.CustomerName) %></td>
<td><%:Html.TextBoxFor(t => t.CustomerName, new { ID = "txtCustomerName" })%></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" onclick="CheckName()" />
</td>
</tr>
</table>
<%--<% Html.EndForm(); %>--%>
</div>
</body>
I need to get t.CustomerName value using JavaScript. I tried as below and it gives me errors.
<head runat="server">
<script type="text/javascript">
function CheckName() {
var value = document.getElementById('<%=t.CustomerName%>').value;
alert(value);
}
function SubmitData() {
var obj = {};
obj.CustomerID = $("#txtCustomerID").val();
obj.CustomerName = $("#txtCustomerName").val();
$.ajax({
url: "CreateNewRetailCustomer?jsonObject=" + JSON.stringify(obj),
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (result.status == "successful") {
document.location.href = '../';
}
}
});
}
</script>
<title>Create Wholesale Customer</title>
</head>
i wrote my controller coding as below :
public ActionResult CreateRetailCustomer()
{
return View();
}
[HttpPost]
public ActionResult CreateRetailCustomer(RetailCustomer retCust)
{
new CustomerService.CustomerServiceClient().SaveRetailCustomer(retCust);
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult CreateRetailCustomer(string jsonObject)
{
var retailCustomer = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Models.RetailCustomer>(jsonObject);
new CustomerService.CustomerServiceClient().SaveRetailCustomer(retailCustomer);
return Json(new { status = "successful" }, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetCustomerList()
{
var custlist = new CustomerService.CustomerServiceClient().GetCustomer().Select(m => new { CustomerId = m.CustomerId, CustomerName = m.CustomerName});
return Json(custlist, JsonRequestBehavior.AllowGet);
}
error:
An error occurred during the compilation of a resource required to
service this request. Please review the following specific error
details and modify your source code appropriately.
I searched and I found similar question asp.net mvc get value from Html.textbox() here. but it doesn't discussed about how to get value from Html.TextBoxFor so how can I do this?
var value = document.getElementById('<%=t.CustomerName%>').value;
This line is causing the error. ASP.NET MVC doesn't generate random client side ids like in Web Forms. They will be the same property name in your model. This line is what you are looking for:
var value = document.getElementById('CustomerName').value;
Also HTML helpers like TextBoxFor() take some delegates as a parameter. t variable you are trying to use is meaningful in the context of a lambda expression(a short way to create delagates and expressions). If you want to reach a model property, use Model variable.
A clean way to get the ID is to use IdFor(). This allows hierarchical IDs to be resolved and avoids hardcoding the string name for the property into your code.
function CheckName() {
var value = document.getElementById('<%:Html.IdFor(t => t.CustomerName) %>').value;
alert(value);
}