简体   繁体   English

使用ASP MVC View进行X-editable,如何将提交的表单POST操作传递给控制器

[英]X-editable with ASP MVC View, how to get the submitted form POST action to the controller

I am using X-Editable Plugin to capture user input, and performing submission to server. 我正在使用X-Editable插件来捕获用户输入,并执行提交到服务器。 I'm getting an error on submission, what should I change to get the x-editable data working with the form. 我在提交时遇到错误,我应该更改什么才能使x-editable数据与表单一起使用。

  1. Do I change the Controller (signature or attribute?), or the Javascript AJAX arguments to get past the submission? 我是否更改了Controller(签名或属性?)或Javascript AJAX参数以通过提交?
  2. for some scenarios, how do I autodetect the change in the inline, X-editable texbox to perform a post right away, when user leaves the box. 对于某些情况,当用户离开框时,如何自动检测内联X可编辑texbox中的更改以立即执行帖子。
  3. What would I need to change in the Javascript to make it work with a partial view 我需要在Javascript中进行哪些更改才能使其与部分视图一起使用
  4. Would it enhance my solution if I were to encapsulate the HTML in a form, and use the user button submission 如果我要在表单中封装HTML,并使用用户按钮提交,它会增强我的解决方案吗?

Javascript: 使用Javascript:

 $('#Application').editable({
     url: function (params) {                      
        return $.ajax({
           url: 'Application/Create',
           type: "POST",
           contentType: 'application/json; charset=utf-8',
           data: JSON.stringify(params),
           dataType: 'json',
           async: true,               
           success: function (response) {
                     alert("Success");
           },
           error: function () {
                     alert("Error in Ajax");
           }
          });
      }
});


HTML:
<!-- language: lang-html -->
<a href="#" id="Application" class="EditableApplication"></a>



<!-- language: C# -->    
[HttpPost]                            
//[Authorize]
public ActionResult Create(String params)
{
var = params;
        //Deserialize and Get params here and create application objeci
Return View();
}

This seemed to work for me ... 这似乎对我有用......

Javascript ... Javascript ...

   $('#searchresult a').editable({
            url: function (params) {
                var requestData = '';
                if (params.name == 'employeeno') 
                    requestData = { UserName: params.pk, EmployeeNo: params.value }
                else
                    return; //perform no update

                return $.ajax({
                        cache: false,
                        async: true,
                        type: 'POST',
                        data: requestData,
                        url: 'EASMUser/UpdateAccountProperty',
                        beforeSend: showWaitCursor('Updating EASM Account ...'),
                        success: function (response) {
                            alert("Success");
                        },
                        error: function (data) {
                            debugger;
                            alert(data);
                        }
                        });
                    }
            }
        );

Model ... 型号......

public class EASMUserViewModel
{
    public string UserName { get; set; }
    public string EmployeeNo { get; set; }
    public string Password { get; set; }
    public List<Entity> Entities {get; set;}

    /// <summary>
    /// Helper method to convert to string
    /// </summary>
    /// <returns></returns>
    public string EntitiesToString()
    {
        if (Entities == null || Entities.Count == 0)
            return string.Empty;

        StringBuilder sb = new StringBuilder(); 
        foreach( Entity pe in Entities)
        {
            string target = sb.Length > 0 ? ",{0}": "{0}";
            sb.AppendFormat(target, Convert.ToInt32(pe)); 
        }

        return sb.ToString(); 
    }

}

Controller Method ... 控制器方法......

    [HttpPost]
    public ActionResult UpdateAccountProperty(EASMUserViewModel easmuser )
    {
        try
        {
            //using a grid with multiple x-editable controls
            if (!string.IsNullOrEmpty(easmuser.EmployeeNo))
            {
                //Updating Employeeno

                //TODO: update db

            }
            else if (!string.IsNullOrEmpty(easmuser.Password))
            {
                //Updating password

                //TODO: update db
            }

            return Content(string.Format("[{0}] updated successfully.", easmuser.UserName));
        }
        catch (Exception exc)
        {
            //TODO: Add logging

            return ThrowJsonError(exc);
        }

    }

Mark up (creating a table body with multiple x-editable controls) ... 标记(创建具有多个x可编辑控件的表体)...

                        <tbody>
                            @foreach (var item in Model)
                            {
                                <tr id="@item.UserName">
                                    <td>@item.UserName</td>
                                    <td><a href="#" id="employeeno" data-name="employeeno" data-type="text" data-title="Enter EmployeeNo" data-pk="@item.UserName">@item.EmployeeNo</a></td>
                                    <td><a href="#" id="password" data-type="text" data-title="Enter Password" data-pk="@item.UserName" >@item.Password</a></td>
                                    <td><a href="#" id="entities" data-type="checklist" 
                                           data-pk="@item.UserName" 
                                           data-source="[{ value: 1, text: 'Entity1' },{ value: 2, text: 'Entity2' },{ value: 3, text: 'Entity3' }, { value: 4, text: 'Entity4' },{ value: 6, text: 'Entity5' }]"
                                           data-title="Select Entities"   
                                           data-value="@item.EntitiesToString()"
                                           >
                                           </a>
                                    </td>
                                    <td>
                                        <button class="btn btn-xs btn-danger" id="@item.UserName" 
                                                data-toggle="tooltip" data-placement="left" 
                                                onclick="deleteEASMUserAccount('@item.UserName');"
                                                title="Delete @item.UserName" >
                                                    <i class="fa fa-times"></i>
                                        </button>
                                    </td>
                                </tr>
                            }

                        </tbody>

I know this is way old but you might find it useful if you've got similar question 我知道这已经过时了但如果你有类似的问题,你可能会觉得它很有用

VIEW 视图

           $('#url').editable({
           url: '@Url.Action("EditProfile","Company")',
            type: 'text',
            pk: @Model.ID,
            name: 'url',
            title: 'Enter URL'
            });

CONTROLLER CONTROLLER

public ActionResult EditProfile(FormCollection fc)
    {

        try
         {
            if (ModelState.IsValid)
            {
                Customer cust = new Customer();
                cust.ID = Convert.ToInt32(fc["pk"]);
                cust.DATE_MODIFIED = DateTime.Now;

                User user = (User)Session["currentuser"];
                cust.MODIFIEDBY = user != null ? user.ID : 0 ;

                //set values based on the x-editable complement from view
                if (fc["name"] == "companyname") cust.BUSINESSNAME = fc["value"];
                if (fc["name"] == "motto") cust.MOTTO = fc["value"];
                if (fc["name"] == "phone") cust.CONTACT_PHONE1 = fc["value"];
                if (fc["name"] == "phone1") cust.CONTACT_PHONE2 = fc["value"];
                if (fc["name"] == "url") cust.CONTACT_URL = fc["value"];
                if (fc["name"] == "about") cust.ABOUT = fc["value"];

                //update Customer Table
                new CustomerRepo().UpdateCustomer(cust);

                //return 200 OK as expected by x-editable
                return new JsonResult();

            }


           // Response.StatusCode = (int)HttpStatusCode.OK;
           // Response.SuppressFormsAuthenticationRedirect = true;
            return Json(new { status = "error", message = "Update Failed. Please try again later" });

        }
        catch(Exception ex)
        {

           // Response.StatusCode = (int)HttpStatusCode.OK;
          //  Response.SuppressFormsAuthenticationRedirect = true;
            return Json(new { status="error", message = "Update Failed. Please try again later" });
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM