Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

javascript - ASP.NET Framework MVC send Razor View data with ajax to the server after validation

I am doing an ASP.NET Framework MVC project and I need to send the combo boxes selected items from below partial view to the server with Jquery Ajax but these combo boxes must be validated at first and then the data must be sent in view model with Ajax to the action (DigestFile(ModelDto Mappings)) in the controller. My project parts is as below :

The partial view as below:

    @using Web.Library.Bases;
    @inherits  Common.DataTransferObjects.Originals.ModelDto
    @{
        Layout = "";
        List<(string Caption, bool IsAsigned, bool IsMandatory, bool IsSelected, string Name, string Title)> dataBaseFields = ViewBag.DataBaseFields;
        int counter = 0;
     }
    <div id="Excel_B" class="editor-block">
        @Html.Hidden("IsNotMatched")
        <div class="block-label">
            <p class="vertical-text">
                ????? ??????
            </p>
        </div>
        <div class="block-content">
            @foreach (var chlItem in dataBaseFields)
            {
                <div id="ExcelFields_G" class="editor-group ">
                    <div id="ExcelFields_L" class="editor-label mandatory">
                        <span class="MappingLabel">@chlItem.Caption :</span>
                    </div>
                    @switch (chlItem.Name)
                    {
                        case "RowNumber":
                            <div id="ExcelFields_A" class="editor-field ">
                                @Html.EditorFor(model => model.RowNumber, "ComboBox")
                                @Html.ValidationMessageFor(model => model.RowNumber)
                            </div>
                            break;
                        case "Name":
                            <div id="ExcelFields_B" class="editor-field ">
                                @Html.EditorFor(model => model.Name, "ComboBox")
                                @Html.ValidationMessageFor(model => model.Name)
                            </div>
                            break;
                        case "Family":
                            <div id="ExcelFields_C" class="editor-field ">
                                @Html.EditorFor(model => model.Family, "ComboBox")
                                @Html.ValidationMessageFor(model => model.Family)
                            </div>
                            break;
                        case "Code":
                            <div id="ExcelFields_D" class="editor-field ">
                                @Html.EditorFor(model => model.Code, "ComboBox")
                                @Html.ValidationMessageFor(model => model.Code)
                            </div>
                            break;
                        case "NationalCode":
                            <div id="ExcelFields_E" class="editor-field ">
                                @Html.EditorFor(model => model.NationalCode, "ComboBox")
                                @Html.ValidationMessageFor(model => model.NationalCode)
                            </div>
                            break;
                        default:
                            break;
            }
            </div>
        }
    </div>
    @if (Model.IsNotMatched > 0)
        {
            <div class="DigestBut" title="Read File">
                <a href="#" class="submitLink" onclick="DigestButtonClicked()">
                    Read File
                </a>
            </div>
        }
</div>
</div>

The View Model as below:

namespace Common.DataTransferObjects.Originals
{
    public class ModelDto
    {
        [Display(Name = "RowNumber")]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
        public string RowNumber { set; get; }

        [Display(Name = "Name")]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
        public string Name { set; get; }

        [Display(Name = "Family")]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
        public string Family { set; get; }

        [Display(Name = "Code")]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
        public string Code { set; get; }

        [Display(Name = "NationalCode")]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(FoundationValidationMessages))]
        public string NationalCode { set; get; }
    }
}

The Action is as below:

public ActionResult DigestFile(ModelDto Mappings)
{
  ....
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is how you have to proceed in case you have many 'entries' to send in same time to save in your controller, but of course you can use it to send only one:

In your view:

<input id="Button1" type="button" value="button" onclick="SaveMe()" />
<script>
function SaveMe() {

    // Get the value of your edit

    var RowNumber0 = $("#RowNumber").val();
    var Name0 = $("#Name").val();
    var Family0 = $("#Family").val();
    var Code0= $("#Code").val();
    var NationalCode0= $("#NationalCode").val();


    // Creat Object

    var lineItems = new Object();
    lineItems.Entrys = new Array();

    // Example Filling your object...

    lineItems.Entrys[0] = new Object({ RowNumber: RowNumber0, Name: Name0, Family: Family0, Code : Code0, NationalCode: NationalCode0 });

    //lineItems.Entrys[1] = ... same logic for your other entries


    // send by ajax to your controller and getting answer ...
    $.ajax({
        type: "POST",
        url: "/Home/AjaxMethodDigestFile",
        data: JSON.stringify({ Entrys: lineItems.Entrys }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) { alert(response.message); },
        failure: function (response) { alert("failure"); },
        error: function (response) { alert("error"); }
    });
}

in your controller:

[HttpPost]
public JsonResult AjaxMethodDigestFile(ICollection<Common.DataTransferObjects.Originals.ModelDto > Entrys)
{
string message = "";
int counter = 0;

foreach (var entry in Entrys)
{
    // How to use this data example
    string RowNumber = entry.RowNumber;
    string Name= entry.Name;
    counter += 1;
    message += "Saved " + ": " + counter + Constants.vbCrLf;
}

// The following lines are not necessary, it's just an example code to know what happen and return it to client side ...
if (counter > 0)
    message = counter.ToString() + " Entrys received" + Constants.vbCrLf + message;
else
    message = "no entrys";


var response = new { counter, message };

return Json(response);

}

EDIT: About the validation

I don't know the library that you are using FoundationValidationMessages so can't help much with this, but I tried a classic way that work:

In Model:

[Required(ErrorMessage = "Required")]
public string RowNumber { set; get; }

In View:

@using (Html.BeginForm("Test2", "Home", FormMethod.Post))
{
...
@Html.EditorFor(model => model.RowNumber)
@Html.ValidationMessageFor(model => model.RowNumber)
...
}

And in your controller :

    [HttpPost]
    public ActionResult Test2(ModelDto um)
    {
        if (ModelState.IsValid)
        {
            return View(um);
        }
        else
        {
            return View();
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...