my action method returning {"success=true,message="work done"} ASP.net MVC 5 - asp.net

Here is my create action method. I want get alert form it when success is true.
public JsonResult Create(Student student ,HttpPostedFileBase img)
{
if (ModelState.IsValid)
{
if (img !=null)
{
var name = Path.GetFileNameWithoutExtension(img.FileName);
var ext = Path.GetExtension(img.FileName);
var filename = name + DateTime.Now.ToString("ddmmyyyff") + ext;
img.SaveAs(Server.MapPath("~/img/"+filename));
student.ImageName = filename;
student.Path = "~/img/" + filename;
}
db.Students.Add(student);
db.SaveChanges();
return Json(new { success = true, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
ViewBag.ClassID = new SelectList(db.Classes, "Id", "Name", student.ClassID);
return new JsonResult { Data = new { success = false, message = "data not saved" } };
}
Here is my ajax function :
function onsub(form) {
$.validations.unobtrusive.parse(form);
if (form.valid()) {
var ajaxConfig = {
type: "POST",
url: form.action,
data: new FormData(form),
success: function (response) {
if (response.success ) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}
}
if ($(form).attr("enctype") == "multipart/form-data") {
ajaxConfig["contentType"] = false;
ajaxConfig["processData"] = false;
}
$.ajax(ajaxConfig);
}
return false;
}
How can I get an alert form it
without reloading the form. I also want to submit images and other files to create an action method.
This is the result that I get after submitting the form:

In your case you are calling Create action which returning the JSON Result and the same Json response is displayed in browser.
Their should be a View page from where you will call this method by using the Ajax call, then you will be able to see your alert message.

Related

Modify BuildApiResponse in ASP.Net Web Api

I am new in ASP.NET MVC Web API. I am trying to modified the return JSon to this format
{
"Error": false,
"Status": 200,
"Response": []
}
Now I able to do that by follow this post https://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information . But the problem is I not able to show ModelState error like 'First name is required' because the code only show the first hit error.
if (error != null)
{
content = null;
//only show the first error
errorMessage = error.Message;
}
So I did some modification, now the code is written as below:
if (error != null)
{
content = null;
foreach(var e in error)
{
//if the error's type is ModelState
if (e.Key.Equals("ModelState"))
{
var allErrors = e.Value;
foreach (var modelError in (IEnumerable<KeyValuePair<string, object>>)allErrors)
{
var msg = modelError;
errorMessage = string.Concat(errorMessage, ", ", ((String[]) modelError.Value)[0]);
}
}
else
{
errorMessage = e.Value.ToString();
}
}
}
Now it's able to show all errors but the code is messy. I am writing this questions to find out what is the proper way to write this kind of code.
You can iterate over all the errors and concatenate them using StringBuilder. String.Join is much faster than Append for less than 1000 items (it is unlikely you will have so many errors in the modelstate object):
public static ValidationResult CheckValid(ModelStateDictionary modelState, string httpName = null)
{
if (!modelState.IsValid)
{
var sb = new StringBuilder();
sb.AppendLine(httpName + " failed: Invalid Json:");
foreach (var pair in modelState)
{
var error = String.Join(";", pair.Value.Errors.Select
(
i =>
{
if (!String.IsNullOrEmpty(i.ErrorMessage))
return i.ErrorMessage;
return i.Exception.Message;
}
));
sb.AppendLine($"Property: {pair.Key} Errors: ({error})");
}
return new ValidationResult(false, sb.ToString());
}
else
return new ValidationResult(true, "");
}

asp.net in OpenFileDialog

I am creating a web server through asp.net.
The source works well in debug mode.
However, after posting to iis, if you go through the source, you will get the error 'HTTP Error 503. The service is unavailable' after about 20 seconds.
I am confident that there is an error in the OpenFileDialog section.
In the past, this code worked well after posting. I do not know what has been modified since then.
Thanks in advance for your help.
.js code
action: function (e, dt, node, config) {
$.ajax({
"url": "/api/Member/ExcelRead",
"type": "POST",
"datatype": 'json',
success: function (data) {
if (data === 'OK') {
alert("성공");
}
},
error: function (response, state, errorCode) {
alert("실패");
}
});
.cs
public class MemberController : ApiController
{
[HttpPost]
public string ExcelRead()
{
ExcelHelper helper = new ExcelHelper();
Thread th = new Thread(helper.ReadExcelData);
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
if (helper.data == null)
return ("NO");
return ("OK");
}
}
public void ReadExcelData()
{
IsRun = false;
OpenFileDialog openFile = new OpenFileDialog();
openFile.DefaultExt = "xlsx";
openFile.Filter = "Excel Files(*.xlsx)|*.xlsx";
DialogResult dresult = openFile.ShowDialog();
if (dresult != DialogResult.OK)
{
return;
}
if (openFile.FileNames.Length > 0)
{
foreach (string filename in openFile.FileNames)
{
//this.textBox1.Text = filename;
}
}
}

Delete Records from a database

I am trying to delete set of records under my ASP.NET Application - API Controller. Here is my code from API Controller:
public JsonResult Delete([FromBody]ICollection<ShoppingItemViewModel> vm)
{
if (ModelState.IsValid)
{
try
{
var items = Mapper.Map<IEnumerable<ShoppingItem>>(vm);
_repository.DeleteValues(items, User.Identity.Name);
return Json(null);
}
catch (Exception Ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(null);
}
}
else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(null);
}
}
And here is my AngularJS Controller part taking care of this:
$scope.RemoveItems = function () {
$scope.isBusy = true;
$http.delete("/api/items", $scope.items)
.then(function (response) {
if (response.statusText == "OK" && response.status == 200) {
//passed
for (var i = $scope.items.length - 1; i > -1; i--) {
if ($scope.items[i].toRemove == true) {
$scope.items.splice(i, 1);
}
}
}
}, function (err) {
$scope.errorMessage = "Error occured: " + err;
}).finally(function () {
$scope.isBusy = false;
});
}
For unknown reason, this works like a charm in my POST method but not in the Delete Method. I believe that the problem might be caused by the fact, that DELETE method only accepts Integer ID?
If that is the case, what is the correct way how to delete multiple items with one call?

Post data with free-jqgrid, what are the code in client and Web API side?

I am using ASP.NET MVC 6 Web API. In the View I use free-jqgrid.
Let's borrow Oleg's free jqgrid data to demonstrate my purpose. We already have the table shown.
Next I am going to add new Vendor. Please notify that there is primary key id(identity column) in the database. We don't want it displaying in the screen.
In VendorRespository.cs, I add the new Vendor as
public void AddVendor(Vendor item)
{
using (VendorDataContext dataContext = new VendorDataContext())
{
dataContext.Database.Connection.ConnectionString = DBUtility.GetSharedConnectionString(
"http://centralized.admin.test.com");
var newVendor = dataContext.Vendors.Create();
newVendor.Company = item.Company;
newVendor.ContactName = item.ContactName;
newVendor.ContactPhone = item.ContactName;
newVendor.UserName = item.UserName;
newVendor.UserKey = item.UserKey;
newVendor.Active = item.Active;
newVendor.FacilityId =item.FacilityId;
newVendor.ClientID = item.ClientID;
dataContext.SaveChanges();
}
}
My questions:
Not sure the script like?
<script>
API_URL = "/VendorManagement/";
function updateDialog(action) {
return {
url: API_URL
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) { }
, modal: true
, onclickSubmit: function (params) {
var list = $("#jqgrid");
var selectedRow = list.getGridParam("selrow");
rowData = list.getRowData(selectedRow);
params.url += rowData.Id;
params.mtype = action;
}
, width: "300"
};
}
jQuery("#jqgrid").jqGrid('navGrid',
{ add: true, edit: true, del: true },
updateDialog('PUT'),
updateDialog('POST'),
updateDialog('DELETE')
);
In the controller, not sure what is the code?
// POST
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
My code has many compiling errors such as
'HttpRequest' does not contain a definition for 'CreateResponse' and the best extension method overload 'HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage, HttpStatusCode, Vendor)' requires a receiver of type 'HttpRequestMessage'
Please help me to get rid of the error and inappropriate code.
EDIT:
I borrowed the code snippet from here.
I need add the code such as
[Microsoft.AspNet.Mvc.HttpGet]
public dynamic GetVendorById(int pkey)
{
return null;
}
And
// POST
[System.Web.Http.HttpPost]
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("/VendorManagement/GetVendorById", new { id = item.pkey });
response.Headers.Location = new Uri(uri);
return response;
}

Transfer data to ApplicationController

I'm trying to do a login module with view master page. First user access to a home page with a login form, when user click login, page should redirect to a UserLoginController first and then redirect to another PanelController which holds all pages with same master page. I want to show different menus by different user's permission. As I refer a article http://www.asp.net/mvc/tutorials/passing-data-to-view-master-pages-cs I create a abstract class ApplicationController, the PanelController inherit it. In the constructor, I want to get the login user's information to identify user's permission, but it seems Request and Session is not available. Pls see code.
First the login Javascript
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$(btnLogin).click(function () {
var sso = $(txtSSO).val();
var pwd = $(txtPwd).val();
if (sso == "")
{ alert("Please input your SSO number"); }
else if (pwd == "")
{ alert("Please input your password"); }
else {
jQuery.ajax(
{ url: '<%:Url.Action("UserLogin", "UserLogin")%>',
data: { sso: sso, pwd: pwd },
success: function (data) {
window.location = '<%: Url.Action("Demo","Panel") %>';
}
}
);
}
});
});
</script>
The UserLoginController
public ActionResult UserLogin()
{
string sso = "";
string pwd = "";
try
{
if (Request.IsAjaxRequest())
{
sso = Request.Params["sso"].ToString();
pwd = Request.Params["pwd"].ToString();
}
Regex reg = new Regex("^[0-9]{9}$");
if (!reg.Match(sso).Success || pwd == "")
{
ViewData["errorMsg"] = "Either your UserID or your Password is incorrect";
return View("Index");
}
SystemAdminEntities entity = new SystemAdminEntities();
var result = entity.ValidateUserLogin(sso, pwd).FirstOrDefault();
if (result == 1)//User is found
{
int isso = Convert.ToInt32(sso);
var dbEmp = (from e in entity.sys_employee
where e.sso == isso
select e);
SysEmployee emp = dbEmp.FirstOrDefault<SysEmployee>();
LogonUserModel currentUser = LogonUserModel.GetUser();
currentUser.CopyUserInfo(emp);
//FormsAuthenticationTicket ticket=new
FormsAuthentication.SetAuthCookie(currentUser.SSO.ToString(), true);
Session.Add("emp", currentUser);
this.Session.Add("sso", currentUser.SSO);
this.Session.Add("empid", currentUser.EmpID);
this.Session.Add("ename", currentUser.EName);
return RedirectToAction("Demo", "Panel");//重定向到 Demo
}
else if (result == 0)//User is not found
{
ViewData["errorMsg"] = "User isn't found";
return View("Index");
}
else if (result == 2)//Password not correct
{
ViewData["errorMsg"] = "Password Error";
return View("Index");
}
return View("Index");
}
catch { return View("Index"); }
}
The ApplicationController
public abstract class ApplicationController : Controller
{
private SystemAdminEntities _entities = new SystemAdminEntities();
public ApplicationController()
{
//根据人员判断权限
int sso = 0;//= Request.Form["sso"].ToString();
try
{
sso = int.Parse(Session["sso"].ToString());
var e = (from emp in _entities.sys_employee//得到对应的用户
where emp.sso == sso
select emp
);
SysEmployee loginUser = e.FirstOrDefault<SysEmployee>();
ViewData["modules"] = loginUser.SysHasPerm;
}
catch
{
ViewData["modules"] = null;
}
}
The PanelController
public class PanelController : ApplicationController
{
//
// GET: /Panel/
public ActionResult Index()
{
return View();
}
public ActionResult Demo()
{
return View();
}
}
ViewData is used in MVC to pass data from Controllor to View
and Tempdata is used to pass data from one Controllor to other
Refer Passing State Between Action Methods
See this example for Step by step -

Resources